This repository has been archived by the owner on Apr 15, 2020. It is now read-only.
forked from ardatan/graphql-tools
-
Notifications
You must be signed in to change notification settings - Fork 5
/
createServerHttpLink.ts
84 lines (72 loc) · 2.14 KB
/
createServerHttpLink.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { concat } from 'apollo-link';
import { createUploadLink, defaultAppendFile } from 'apollo-upload-client';
import { isExtractableFile } from 'extract-files';
import KnownLengthFormData, { AppendOptions } from 'form-data';
import fetch from 'node-fetch';
import { AwaitVariablesLink } from './AwaitVariablesLink';
const hasOwn = Object.prototype.hasOwnProperty;
class FormData extends KnownLengthFormData {
private hasUnknowableLength: boolean;
constructor(options?: any) {
super(options);
this.hasUnknowableLength = false;
}
public append(
key: string,
value: any,
optionsOrFilename: AppendOptions | string = {},
): void {
// allow filename as single option
const options: AppendOptions =
typeof optionsOrFilename === 'string'
? { filename: optionsOrFilename }
: optionsOrFilename;
// empty or either doesn't have path or not an http response
if (
!options.knownLength &&
!Buffer.isBuffer(value) &&
typeof value !== 'string' &&
!value.path &&
!(value.readable && hasOwn.call(value, 'httpVersion'))
) {
this.hasUnknowableLength = true;
}
super.append(key, value, options);
}
public getLength(
callback: (err: Error | null, length: number) => void,
): void {
if (this.hasUnknowableLength) {
return null;
}
return super.getLength(callback);
}
public getLengthSync(): number {
if (this.hasUnknowableLength) {
return null;
}
// eslint-disable-next-line no-sync
return super.getLengthSync();
}
}
export const createServerHttpLink = (options: any) =>
concat(
new AwaitVariablesLink(),
createUploadLink({
...options,
fetch,
FormData,
isExtractableFile: (value: any) =>
isExtractableFile(value) || value?.createReadStream,
appendFile: (form: FormData, index: string, file: any) => {
if (file.createReadStream != null) {
form.append(index, file.createReadStream(), {
filename: file.filename,
contentType: file.mimetype,
});
} else {
defaultAppendFile(index, file);
}
},
}),
);