graphql-upload-nextjs 2.0.11 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -5
- package/index.d.ts +1 -0
- package/index.js +47 -9
- package/package.json +16 -14
package/README.md
CHANGED
|
@@ -57,6 +57,7 @@ Resolver code stays the same — `filename`, `mimetype`, `encoding`, and `create
|
|
|
57
57
|
|
|
58
58
|
```typescript
|
|
59
59
|
import path from 'node:path'
|
|
60
|
+
import { randomUUID } from 'node:crypto'
|
|
60
61
|
import { createWriteStream } from 'node:fs'
|
|
61
62
|
import { pipeline } from 'node:stream'
|
|
62
63
|
import { gql } from '@apollo/client' // Optional: syntax highlighting only.
|
|
@@ -99,13 +100,14 @@ const resolvers = {
|
|
|
99
100
|
): Promise<FileResponse> => {
|
|
100
101
|
const { createReadStream, encoding, filename, fileSize, mimetype } = await file;
|
|
101
102
|
const safeName = path.basename(filename);
|
|
103
|
+
const storedName = randomUUID();
|
|
102
104
|
return new Promise((resolve, reject) => {
|
|
103
105
|
pipeline(
|
|
104
106
|
createReadStream(),
|
|
105
|
-
createWriteStream(`./uploads/${
|
|
107
|
+
createWriteStream(`./uploads/${storedName}`, { flags: "wx" }),
|
|
106
108
|
(error) => {
|
|
107
109
|
if (error) reject(new Error("Error during file upload."));
|
|
108
|
-
else resolve({ encoding, filename: safeName, fileSize, mimetype, uri: `/${
|
|
110
|
+
else resolve({ encoding, filename: safeName, fileSize, mimetype, uri: `/${storedName}` });
|
|
109
111
|
},
|
|
110
112
|
);
|
|
111
113
|
});
|
|
@@ -117,13 +119,14 @@ const resolvers = {
|
|
|
117
119
|
const resolvedFiles = await Promise.all(files);
|
|
118
120
|
return Promise.all(resolvedFiles.map(async ({ createReadStream, encoding, filename, fileSize, mimetype }) => {
|
|
119
121
|
const safeName = path.basename(filename);
|
|
122
|
+
const storedName = randomUUID();
|
|
120
123
|
return new Promise<FileResponse>((resolve, reject) => {
|
|
121
124
|
pipeline(
|
|
122
125
|
createReadStream(),
|
|
123
|
-
createWriteStream(`./uploads/${
|
|
126
|
+
createWriteStream(`./uploads/${storedName}`, { flags: "wx" }),
|
|
124
127
|
(error) => {
|
|
125
128
|
if (error) reject(new Error(`Error during upload of ${safeName}.`));
|
|
126
|
-
else resolve({ encoding, filename: safeName, fileSize, mimetype, uri: `/${
|
|
129
|
+
else resolve({ encoding, filename: safeName, fileSize, mimetype, uri: `/${storedName}` });
|
|
127
130
|
},
|
|
128
131
|
);
|
|
129
132
|
});
|
|
@@ -176,10 +179,14 @@ await uploadProcess(request, context, server, {
|
|
|
176
179
|
|---|---|---|---|
|
|
177
180
|
| `allowedTypes` | `string[]` | `undefined` | Restrict MIME types. Checked against the detected MIME type; unknown binary files are `application/octet-stream`. |
|
|
178
181
|
| `maxFileSize` | `number` | `undefined` | Max file size in bytes. Must be finite and non-negative. Returns 413 if exceeded. |
|
|
179
|
-
| `maxFiles` | `number` | `undefined` | Max files per request. Must be
|
|
182
|
+
| `maxFiles` | `number` | `undefined` | Max files per request, including unmapped files. Must be a non-negative safe integer. Returns 413 if exceeded. |
|
|
180
183
|
|
|
181
184
|
### Client Usage
|
|
182
185
|
|
|
186
|
+
Multipart requests must send `Apollo-Require-Preflight: true` (or a non-empty `X-Apollo-Operation-Name` header). Configure your upload link with `headers: { "Apollo-Require-Preflight": "true" }`. This forces browser preflight and protects the direct execution path from cross-site form submissions. Only allow trusted origins in your CORS policy.
|
|
187
|
+
|
|
188
|
+
Map paths must target existing `null` placeholders inside operation variables. Single and batched requests preserve `operationName`.
|
|
189
|
+
|
|
183
190
|
When using a GraphQL client library ([apollo-upload-client](https://npm.im/apollo-upload-client), [urql](https://npm.im/@urql/exchange-multipart-fetch), [extract-files](https://npm.im/extract-files)), file uploads are constructed automatically per the spec.
|
|
184
191
|
|
|
185
192
|
```typescript
|
package/index.d.ts
CHANGED
package/index.js
CHANGED
|
@@ -64,7 +64,7 @@ async function collectResponse(response) {
|
|
|
64
64
|
}
|
|
65
65
|
/** Extracts File entries from multipart FormData. */
|
|
66
66
|
async function extractFiles(formData) {
|
|
67
|
-
const files =
|
|
67
|
+
const files = Object.create(null);
|
|
68
68
|
for (const [key, value] of formData.entries()) {
|
|
69
69
|
if (value instanceof globalThis.File) {
|
|
70
70
|
files[key] = value;
|
|
@@ -106,7 +106,7 @@ async function processUpload(file, allowedTypes) {
|
|
|
106
106
|
}
|
|
107
107
|
else {
|
|
108
108
|
try {
|
|
109
|
-
if (await isText(
|
|
109
|
+
if (await isText(null, headerBuffer)) {
|
|
110
110
|
mimetype = 'text/plain';
|
|
111
111
|
}
|
|
112
112
|
}
|
|
@@ -158,6 +158,9 @@ function validateOperation(operation, label) {
|
|
|
158
158
|
if (operation.variables !== undefined && !isObjectRecord(operation.variables)) {
|
|
159
159
|
return `Invalid ${label}: expected variables to be an object when provided.`;
|
|
160
160
|
}
|
|
161
|
+
if (operation.operationName !== undefined && typeof operation.operationName !== 'string') {
|
|
162
|
+
return `Invalid ${label}: expected operationName to be a string when provided.`;
|
|
163
|
+
}
|
|
161
164
|
return null;
|
|
162
165
|
}
|
|
163
166
|
/** Validates upload process settings before request body processing starts. */
|
|
@@ -168,9 +171,13 @@ function validateSettings(settings) {
|
|
|
168
171
|
return 'Invalid maxFileSize setting: expected a finite non-negative number.';
|
|
169
172
|
}
|
|
170
173
|
if (settings?.maxFiles !== undefined && (typeof settings.maxFiles !== 'number' ||
|
|
171
|
-
!Number.
|
|
174
|
+
!Number.isSafeInteger(settings.maxFiles) ||
|
|
172
175
|
settings.maxFiles < 0)) {
|
|
173
|
-
return 'Invalid maxFiles setting: expected a
|
|
176
|
+
return 'Invalid maxFiles setting: expected a non-negative safe integer.';
|
|
177
|
+
}
|
|
178
|
+
if (settings?.allowedTypes !== undefined && (!Array.isArray(settings.allowedTypes) ||
|
|
179
|
+
settings.allowedTypes.some(type => typeof type !== 'string' || !type.trim()))) {
|
|
180
|
+
return 'Invalid allowedTypes setting: expected an array of non-empty MIME types.';
|
|
174
181
|
}
|
|
175
182
|
return null;
|
|
176
183
|
}
|
|
@@ -243,12 +250,18 @@ export function validateMap(map) {
|
|
|
243
250
|
/** Processes a GraphQL multipart request with file uploads. Supports batching per the spec. */
|
|
244
251
|
export async function uploadProcess(request, contextValueInput, server, settings) {
|
|
245
252
|
try {
|
|
253
|
+
// Multipart forms can bypass browser preflight and Apollo's executeOperation skips HTTP CSRF checks.
|
|
254
|
+
if (!request.headers.get('apollo-require-preflight')?.trim() &&
|
|
255
|
+
!request.headers.get('x-apollo-operation-name')?.trim()) {
|
|
256
|
+
return NextResponse.json({ errors: [{ message: 'Upload requests require an Apollo-Require-Preflight header.' }] }, { status: 400 });
|
|
257
|
+
}
|
|
246
258
|
const settingsError = validateSettings(settings);
|
|
247
259
|
if (settingsError) {
|
|
248
260
|
return NextResponse.json({ errors: [{ message: settingsError }] }, { status: 400 });
|
|
249
261
|
}
|
|
250
262
|
const formData = await request.formData();
|
|
251
263
|
const files = await extractFiles(formData);
|
|
264
|
+
const fileCount = Array.from(formData.values()).filter(value => value instanceof globalThis.File).length;
|
|
252
265
|
const mapRaw = formData.get('map');
|
|
253
266
|
const operationsRaw = formData.get('operations');
|
|
254
267
|
if (!mapRaw || !operationsRaw || typeof mapRaw !== 'string' || typeof operationsRaw !== 'string') {
|
|
@@ -290,14 +303,38 @@ export async function uploadProcess(request, contextValueInput, server, settings
|
|
|
290
303
|
return NextResponse.json({ errors: [{ message: operationError }] }, { status: 400 });
|
|
291
304
|
}
|
|
292
305
|
}
|
|
293
|
-
|
|
294
|
-
if (
|
|
306
|
+
const isBatch = Array.isArray(parsedOperations);
|
|
307
|
+
if (isBatch && parsedOperations.length === 0) {
|
|
308
|
+
return NextResponse.json({ errors: [{ message: 'Operations batch cannot be empty.' }] }, { status: 400 });
|
|
309
|
+
}
|
|
310
|
+
for (const paths of Object.values(map)) {
|
|
311
|
+
for (const filePath of paths) {
|
|
312
|
+
const segments = filePath.split('.');
|
|
313
|
+
const offset = isBatch ? 1 : 0;
|
|
314
|
+
if ((isBatch && (!/^(0|[1-9]\d*)$/.test(segments[0]) ||
|
|
315
|
+
Number(segments[0]) >= parsedOperations.length)) ||
|
|
316
|
+
segments[offset] !== 'variables' || segments.length <= offset + 1) {
|
|
317
|
+
return NextResponse.json({ errors: [{ message: 'File paths must target operation variables.' }] }, { status: 400 });
|
|
318
|
+
}
|
|
319
|
+
let target = parsedOperations;
|
|
320
|
+
for (const segment of segments) {
|
|
321
|
+
if (target === null || typeof target !== 'object' || !Object.hasOwn(target, segment)) {
|
|
322
|
+
return NextResponse.json({ errors: [{ message: 'File paths must reference existing null placeholders.' }] }, { status: 400 });
|
|
323
|
+
}
|
|
324
|
+
target = target[segment];
|
|
325
|
+
}
|
|
326
|
+
if (target !== null) {
|
|
327
|
+
return NextResponse.json({ errors: [{ message: 'File paths must reference existing null placeholders.' }] }, { status: 400 });
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
// Include unmapped files in the request limit.
|
|
332
|
+
if (settings?.maxFiles !== undefined && Math.max(Object.keys(map).length, fileCount) > settings.maxFiles) {
|
|
295
333
|
return NextResponse.json({ errors: [{ message: `${settings.maxFiles} max file uploads exceeded.` }] }, { status: 413 });
|
|
296
334
|
}
|
|
297
335
|
// Normalize operations into a keyed object for path resolution.
|
|
298
336
|
// Single: paths are "variables.file" → use the operation object directly.
|
|
299
337
|
// Batch: paths are "0.variables.file" → use indices as keys in a wrapper object.
|
|
300
|
-
const isBatch = Array.isArray(parsedOperations);
|
|
301
338
|
let operationsRoot;
|
|
302
339
|
if (isBatch) {
|
|
303
340
|
const batchOperations = parsedOperations;
|
|
@@ -354,12 +391,13 @@ export async function uploadProcess(request, contextValueInput, server, settings
|
|
|
354
391
|
const sortedKeys = Object.keys(operationsRoot).sort((a, b) => Number(a) - Number(b));
|
|
355
392
|
for (const key of sortedKeys) {
|
|
356
393
|
const op = operationsRoot[key];
|
|
357
|
-
const response = await server.executeOperation({ query: op.query, variables: op.variables || {} }, { contextValue: contextValueInput });
|
|
394
|
+
const response = await server.executeOperation({ query: op.query, variables: op.variables || {}, ...(op.operationName !== undefined && { operationName: op.operationName }) }, { contextValue: contextValueInput });
|
|
358
395
|
results.push(await collectResponse(response));
|
|
359
396
|
}
|
|
360
397
|
return NextResponse.json(results);
|
|
361
398
|
}
|
|
362
|
-
const
|
|
399
|
+
const operation = operationsRoot;
|
|
400
|
+
const response = await server.executeOperation({ query: operation.query, variables: operation.variables || {}, ...(operation.operationName !== undefined && { operationName: operation.operationName }) }, { contextValue: contextValueInput });
|
|
363
401
|
return NextResponse.json(await collectResponse(response));
|
|
364
402
|
}
|
|
365
403
|
catch (error) {
|
package/package.json
CHANGED
|
@@ -7,21 +7,18 @@
|
|
|
7
7
|
"url": "https://github.com/lafittemehdy/graphql-upload-nextjs/issues"
|
|
8
8
|
},
|
|
9
9
|
"dependencies": {
|
|
10
|
-
"file-type": "^22.0
|
|
10
|
+
"file-type": "^22.2.0",
|
|
11
11
|
"istextorbinary": "^9.5.0"
|
|
12
12
|
},
|
|
13
13
|
"description": "The middleware and Upload scalar in this package enable GraphQL multipart requests (file uploads via queries and mutations) in your Apollo Server Next.js integration.",
|
|
14
14
|
"devDependencies": {
|
|
15
|
-
"@types/
|
|
16
|
-
"@types/node": "^25.9.3",
|
|
15
|
+
"@types/node": "^26.6.5",
|
|
17
16
|
"graphql": "^16.14.2",
|
|
18
17
|
"husky": "^9.1.7",
|
|
19
|
-
"
|
|
20
|
-
"
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
"typescript": "^6.0.3",
|
|
24
|
-
"undici": "^8.7.0"
|
|
18
|
+
"next": "^16.4.2",
|
|
19
|
+
"typescript": "^7.0.2",
|
|
20
|
+
"undici": "^8.12.3",
|
|
21
|
+
"vitest": "^5.0.5"
|
|
25
22
|
},
|
|
26
23
|
"files": [
|
|
27
24
|
"CODE_OF_CONDUCT.md",
|
|
@@ -52,9 +49,14 @@
|
|
|
52
49
|
"main": "index.js",
|
|
53
50
|
"name": "graphql-upload-nextjs",
|
|
54
51
|
"overrides": {
|
|
55
|
-
"postcss": "8.5.
|
|
52
|
+
"postcss": "8.5.31",
|
|
53
|
+
"@graphql-tools/utils": "13.0.2",
|
|
54
|
+
"@fastify/busboy": "3.2.3",
|
|
55
|
+
"qs": "6.16.1",
|
|
56
|
+
"source-map-js": "1.2.2",
|
|
57
|
+
"body-parser": "2.3.0"
|
|
56
58
|
},
|
|
57
|
-
"packageManager": "npm@
|
|
59
|
+
"packageManager": "npm@12.2.0",
|
|
58
60
|
"peerDependencies": {
|
|
59
61
|
"@apollo/server": "^5.0.0",
|
|
60
62
|
"graphql": "^16.0.0",
|
|
@@ -70,13 +72,13 @@
|
|
|
70
72
|
},
|
|
71
73
|
"scripts": {
|
|
72
74
|
"build": "tsc",
|
|
73
|
-
"dev": "tsc
|
|
75
|
+
"dev": "tsc --watch",
|
|
74
76
|
"prepublishOnly": "npm run build && npm test",
|
|
75
77
|
"start": "tsc && node index.js",
|
|
76
|
-
"test": "
|
|
78
|
+
"test": "vitest run",
|
|
77
79
|
"prepare": "husky || exit 0"
|
|
78
80
|
},
|
|
79
81
|
"type": "module",
|
|
80
82
|
"types": "index.d.ts",
|
|
81
|
-
"version": "
|
|
83
|
+
"version": "3.0.0"
|
|
82
84
|
}
|