graphql-upload-nextjs 3.0.0 → 3.1.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/CONTRIBUTING.md +6 -3
- package/README.md +83 -262
- package/SECURITY.md +3 -3
- package/core.d.ts +107 -0
- package/core.js +341 -0
- package/index.d.ts +7 -73
- package/index.js +36 -390
- package/package.json +24 -15
- package/streaming.d.ts +22 -0
- package/streaming.js +269 -0
package/index.js
CHANGED
|
@@ -1,407 +1,53 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
import { Readable } from 'stream';
|
|
6
|
-
const DEFAULT_MIME_TYPE = 'application/octet-stream';
|
|
7
|
-
/**
|
|
8
|
-
* Represents an instance of a file upload.
|
|
9
|
-
* Holds a promise that resolves with the file details once processed.
|
|
10
|
-
*/
|
|
11
|
-
export class Upload {
|
|
12
|
-
file;
|
|
13
|
-
promise;
|
|
14
|
-
reject = () => { };
|
|
15
|
-
resolve = () => { };
|
|
16
|
-
constructor() {
|
|
17
|
-
this.promise = new Promise((resolve, reject) => {
|
|
18
|
-
this.resolve = (file) => {
|
|
19
|
-
this.file = file;
|
|
20
|
-
resolve(file);
|
|
21
|
-
};
|
|
22
|
-
this.reject = reject;
|
|
23
|
-
});
|
|
24
|
-
this.promise.catch(() => { });
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
/** Custom GraphQL scalar type for handling file uploads. */
|
|
28
|
-
export const GraphQLUpload = new GraphQLScalarType({
|
|
29
|
-
description: 'The Upload scalar type represents a file upload.',
|
|
30
|
-
name: 'Upload',
|
|
31
|
-
parseLiteral(node) {
|
|
32
|
-
throw new GraphQLError('Upload literal unsupported.', { nodes: node });
|
|
33
|
-
},
|
|
34
|
-
parseValue(value) {
|
|
35
|
-
if (value instanceof Upload)
|
|
36
|
-
return value.promise;
|
|
37
|
-
throw new GraphQLError('Upload value invalid.');
|
|
38
|
-
},
|
|
39
|
-
serialize() {
|
|
40
|
-
throw new GraphQLError('Upload serialization unsupported.');
|
|
41
|
-
},
|
|
42
|
-
});
|
|
43
|
-
/** Converts a Buffer into a Node.js readable stream. */
|
|
44
|
-
export function bufferToStream(buffer) {
|
|
45
|
-
const stream = new Readable();
|
|
46
|
-
stream.push(buffer);
|
|
47
|
-
stream.push(null);
|
|
48
|
-
return stream;
|
|
49
|
-
}
|
|
50
|
-
/** Collects a GraphQL response into a serializable result object. */
|
|
51
|
-
async function collectResponse(response) {
|
|
52
|
-
if (response.body.kind === 'single') {
|
|
53
|
-
return response.body.singleResult;
|
|
54
|
-
}
|
|
55
|
-
if (response.body.kind === 'incremental') {
|
|
56
|
-
const { initialResult, subsequentResults } = response.body;
|
|
57
|
-
const collected = [];
|
|
58
|
-
for await (const result of subsequentResults) {
|
|
59
|
-
collected.push(result);
|
|
60
|
-
}
|
|
61
|
-
return { initialResult, subsequentResults: collected };
|
|
62
|
-
}
|
|
63
|
-
return { errors: [{ message: 'Unexpected server response format' }] };
|
|
64
|
-
}
|
|
65
|
-
/** Extracts File entries from multipart FormData. */
|
|
66
|
-
async function extractFiles(formData) {
|
|
67
|
-
const files = Object.create(null);
|
|
68
|
-
for (const [key, value] of formData.entries()) {
|
|
69
|
-
if (value instanceof globalThis.File) {
|
|
70
|
-
files[key] = value;
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
return files;
|
|
74
|
-
}
|
|
75
|
-
/** Parses JSON for the operations field. Accepts objects or arrays (for batching per spec). */
|
|
76
|
-
export function parseOperationsJSON(input) {
|
|
77
|
-
let result;
|
|
78
|
-
try {
|
|
79
|
-
result = JSON.parse(input);
|
|
80
|
-
}
|
|
81
|
-
catch {
|
|
82
|
-
throw new Error('Invalid JSON in the operations multipart field.');
|
|
83
|
-
}
|
|
84
|
-
if (typeof result !== 'object' || result === null) {
|
|
85
|
-
throw new Error('Invalid type for the operations multipart field.');
|
|
86
|
-
}
|
|
87
|
-
return result;
|
|
88
|
-
}
|
|
89
|
-
/**
|
|
90
|
-
* Processes a file from FormData, detects its MIME type via magic bytes,
|
|
91
|
-
* and returns a resolved Upload instance with streaming file access.
|
|
92
|
-
*/
|
|
93
|
-
async function processUpload(file, allowedTypes) {
|
|
94
|
-
if (!file.name || typeof file.size !== 'number' || !Number.isFinite(file.size) || file.size < 0) {
|
|
95
|
-
throw new Error('Invalid file properties: name or size is missing or invalid.');
|
|
96
|
-
}
|
|
97
|
-
const blob = file;
|
|
98
|
-
// Only read the first 4100 bytes for MIME type detection via magic bytes.
|
|
99
|
-
// This avoids buffering the entire file into memory.
|
|
100
|
-
const DETECTION_BYTES = 4100;
|
|
101
|
-
const headerBuffer = Buffer.from(await blob.slice(0, DETECTION_BYTES).arrayBuffer());
|
|
102
|
-
const fileTypeInfo = await fileTypeFromBuffer(new Uint8Array(headerBuffer.buffer, headerBuffer.byteOffset, headerBuffer.byteLength));
|
|
103
|
-
let mimetype = DEFAULT_MIME_TYPE;
|
|
104
|
-
if (fileTypeInfo) {
|
|
105
|
-
mimetype = fileTypeInfo.mime;
|
|
106
|
-
}
|
|
107
|
-
else {
|
|
108
|
-
try {
|
|
109
|
-
if (await isText(null, headerBuffer)) {
|
|
110
|
-
mimetype = 'text/plain';
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
catch {
|
|
114
|
-
// Fallback: isText detection failed, keeping the unknown binary default.
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
if (allowedTypes && !allowedTypes.includes(mimetype)) {
|
|
118
|
-
throw new Error(`File type ${mimetype} is not allowed. Allowed types: ${allowedTypes.join(', ')}`);
|
|
119
|
-
}
|
|
120
|
-
const upload = new Upload();
|
|
121
|
-
upload.resolve({
|
|
122
|
-
createReadStream: () => Readable.fromWeb(blob.stream()),
|
|
123
|
-
encoding: 'binary',
|
|
124
|
-
fileSize: file.size,
|
|
125
|
-
filename: file.name,
|
|
126
|
-
mimetype,
|
|
127
|
-
});
|
|
128
|
-
return upload;
|
|
129
|
-
}
|
|
130
|
-
/** Parses and validates a JSON string, ensuring it resolves to a non-null object (rejects arrays). */
|
|
131
|
-
export function sanitizeAndValidateJSON(input) {
|
|
132
|
-
let result;
|
|
133
|
-
try {
|
|
134
|
-
result = JSON.parse(input);
|
|
135
|
-
}
|
|
136
|
-
catch (error) {
|
|
137
|
-
throw new Error(`Invalid JSON input: ${error.message}`);
|
|
138
|
-
}
|
|
139
|
-
if (typeof result !== 'object' || result === null || Array.isArray(result)) {
|
|
140
|
-
throw new Error('Invalid JSON structure: expected a non-null object.');
|
|
141
|
-
}
|
|
142
|
-
return result;
|
|
143
|
-
}
|
|
144
|
-
/** Dangerous property names that could lead to prototype pollution. */
|
|
145
|
-
const BLOCKED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
146
|
-
/** Checks whether a value is a plain object record suitable for GraphQL variables. */
|
|
147
|
-
function isObjectRecord(value) {
|
|
148
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
149
|
-
}
|
|
150
|
-
/** Validates the minimal GraphQL operation shape required for execution. */
|
|
151
|
-
function validateOperation(operation, label) {
|
|
152
|
-
if (!isObjectRecord(operation)) {
|
|
153
|
-
return `Invalid ${label}: expected an operation object.`;
|
|
154
|
-
}
|
|
155
|
-
if (typeof operation.query !== 'string') {
|
|
156
|
-
return `Invalid ${label}: expected query to be a string.`;
|
|
157
|
-
}
|
|
158
|
-
if (operation.variables !== undefined && !isObjectRecord(operation.variables)) {
|
|
159
|
-
return `Invalid ${label}: expected variables to be an object when provided.`;
|
|
160
|
-
}
|
|
161
|
-
if (operation.operationName !== undefined && typeof operation.operationName !== 'string') {
|
|
162
|
-
return `Invalid ${label}: expected operationName to be a string when provided.`;
|
|
163
|
-
}
|
|
164
|
-
return null;
|
|
165
|
-
}
|
|
166
|
-
/** Validates upload process settings before request body processing starts. */
|
|
167
|
-
function validateSettings(settings) {
|
|
168
|
-
if (settings?.maxFileSize !== undefined && (typeof settings.maxFileSize !== 'number' ||
|
|
169
|
-
!Number.isFinite(settings.maxFileSize) ||
|
|
170
|
-
settings.maxFileSize < 0)) {
|
|
171
|
-
return 'Invalid maxFileSize setting: expected a finite non-negative number.';
|
|
172
|
-
}
|
|
173
|
-
if (settings?.maxFiles !== undefined && (typeof settings.maxFiles !== 'number' ||
|
|
174
|
-
!Number.isSafeInteger(settings.maxFiles) ||
|
|
175
|
-
settings.maxFiles < 0)) {
|
|
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.';
|
|
181
|
-
}
|
|
182
|
-
return null;
|
|
183
|
-
}
|
|
184
|
-
/** Sets a value at a dot-notation path in a nested object, creating intermediate containers as needed. */
|
|
185
|
-
export function setValueAtPath(obj, path, value) {
|
|
186
|
-
const keys = path.split('.');
|
|
187
|
-
let current = obj;
|
|
188
|
-
for (let i = 0; i < keys.length - 1; i++) {
|
|
189
|
-
const key = keys[i];
|
|
190
|
-
if (BLOCKED_KEYS.has(key)) {
|
|
191
|
-
throw new Error(`Invalid path segment: '${key}' is not allowed.`);
|
|
192
|
-
}
|
|
193
|
-
const nextKeyIsArrayIndex = /^\d+$/.test(keys[i + 1]);
|
|
194
|
-
if (!current[key] ||
|
|
195
|
-
typeof current[key] !== 'object' ||
|
|
196
|
-
(nextKeyIsArrayIndex && !Array.isArray(current[key])) ||
|
|
197
|
-
(!nextKeyIsArrayIndex && Array.isArray(current[key]))) {
|
|
198
|
-
current[key] = nextKeyIsArrayIndex ? [] : {};
|
|
199
|
-
}
|
|
200
|
-
current = current[key];
|
|
201
|
-
}
|
|
202
|
-
const finalKey = keys[keys.length - 1];
|
|
203
|
-
if (BLOCKED_KEYS.has(finalKey)) {
|
|
204
|
-
throw new Error(`Invalid path segment: '${finalKey}' is not allowed.`);
|
|
205
|
-
}
|
|
206
|
-
current[finalKey] = value;
|
|
207
|
-
}
|
|
208
|
-
/** Converts a Node.js readable stream into a Buffer by collecting all chunks. */
|
|
209
|
-
export async function streamToBuffer(stream) {
|
|
210
|
-
const chunks = [];
|
|
211
|
-
for await (const chunk of stream) {
|
|
212
|
-
if (Buffer.isBuffer(chunk)) {
|
|
213
|
-
chunks.push(chunk);
|
|
214
|
-
}
|
|
215
|
-
else if (typeof chunk === 'string') {
|
|
216
|
-
chunks.push(Buffer.from(chunk));
|
|
217
|
-
}
|
|
218
|
-
else {
|
|
219
|
-
chunks.push(Buffer.from(chunk));
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
return Buffer.concat(chunks);
|
|
223
|
-
}
|
|
224
|
-
/** Validates that each map entry is an array of string paths. */
|
|
225
|
-
export function validateMap(map) {
|
|
226
|
-
for (const [key, paths] of Object.entries(map)) {
|
|
227
|
-
if (!Array.isArray(paths)) {
|
|
228
|
-
return `Invalid type for map entry '${key}': expected an array of paths.`;
|
|
229
|
-
}
|
|
230
|
-
for (const p of paths) {
|
|
231
|
-
if (typeof p !== 'string') {
|
|
232
|
-
return `Invalid path in map entry '${key}': expected string.`;
|
|
233
|
-
}
|
|
234
|
-
if (!p) {
|
|
235
|
-
return `Invalid path in map entry '${key}': path cannot be empty.`;
|
|
236
|
-
}
|
|
237
|
-
const segments = p.split('.');
|
|
238
|
-
for (const segment of segments) {
|
|
239
|
-
if (!segment) {
|
|
240
|
-
return `Invalid path in map entry '${key}': path cannot contain empty segments.`;
|
|
241
|
-
}
|
|
242
|
-
if (BLOCKED_KEYS.has(segment)) {
|
|
243
|
-
return `Invalid path segment in map entry '${key}': '${segment}' is not allowed.`;
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
return null;
|
|
249
|
-
}
|
|
250
|
-
/** Processes a GraphQL multipart request with file uploads. Supports batching per the spec. */
|
|
1
|
+
import { UploadRequestError, checkUploadRequest, executeOperations, prepareOperations, processUpload, uploadErrorResponse, } from './core.js';
|
|
2
|
+
export { GraphQLUpload, Upload, bufferToStream, parseOperationsJSON, sanitizeAndValidateJSON, setValueAtPath, streamToBuffer, validateMap, } from './core.js';
|
|
3
|
+
export { uploadProcessStreaming } from './streaming.js';
|
|
4
|
+
/** Fully receives files before executing GraphQL; existing callers retain numeric file sizes. */
|
|
251
5
|
export async function uploadProcess(request, contextValueInput, server, settings) {
|
|
252
6
|
try {
|
|
253
|
-
|
|
254
|
-
|
|
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
|
-
}
|
|
258
|
-
const settingsError = validateSettings(settings);
|
|
259
|
-
if (settingsError) {
|
|
260
|
-
return NextResponse.json({ errors: [{ message: settingsError }] }, { status: 400 });
|
|
261
|
-
}
|
|
262
|
-
const formData = await request.formData();
|
|
263
|
-
const files = await extractFiles(formData);
|
|
264
|
-
const fileCount = Array.from(formData.values()).filter(value => value instanceof globalThis.File).length;
|
|
265
|
-
const mapRaw = formData.get('map');
|
|
266
|
-
const operationsRaw = formData.get('operations');
|
|
267
|
-
if (!mapRaw || !operationsRaw || typeof mapRaw !== 'string' || typeof operationsRaw !== 'string') {
|
|
268
|
-
return NextResponse.json({ errors: [{ message: 'Missing or invalid map/operations in form data.' }] }, { status: 400 });
|
|
269
|
-
}
|
|
270
|
-
const mapString = mapRaw;
|
|
271
|
-
const operationsString = operationsRaw;
|
|
272
|
-
// Parse and validate the map field (must be an object, not array).
|
|
273
|
-
let map;
|
|
274
|
-
try {
|
|
275
|
-
map = sanitizeAndValidateJSON(mapString);
|
|
276
|
-
}
|
|
277
|
-
catch {
|
|
278
|
-
return NextResponse.json({ errors: [{ message: 'Invalid JSON in the map multipart field.' }] }, { status: 400 });
|
|
279
|
-
}
|
|
280
|
-
const mapError = validateMap(map);
|
|
281
|
-
if (mapError) {
|
|
282
|
-
return NextResponse.json({ errors: [{ message: mapError }] }, { status: 400 });
|
|
283
|
-
}
|
|
284
|
-
// Parse the operations field (object or array for batching).
|
|
285
|
-
let parsedOperations;
|
|
7
|
+
checkUploadRequest(request.headers, settings);
|
|
8
|
+
let formData;
|
|
286
9
|
try {
|
|
287
|
-
|
|
10
|
+
formData = await request.formData();
|
|
288
11
|
}
|
|
289
12
|
catch {
|
|
290
|
-
|
|
291
|
-
}
|
|
292
|
-
if (Array.isArray(parsedOperations)) {
|
|
293
|
-
for (let i = 0; i < parsedOperations.length; i++) {
|
|
294
|
-
const operationError = validateOperation(parsedOperations[i], `operation at index ${i}`);
|
|
295
|
-
if (operationError) {
|
|
296
|
-
return NextResponse.json({ errors: [{ message: operationError }] }, { status: 400 });
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
else {
|
|
301
|
-
const operationError = validateOperation(parsedOperations, 'operation');
|
|
302
|
-
if (operationError) {
|
|
303
|
-
return NextResponse.json({ errors: [{ message: operationError }] }, { status: 400 });
|
|
304
|
-
}
|
|
13
|
+
throw new UploadRequestError('Invalid multipart request body.');
|
|
305
14
|
}
|
|
306
|
-
const
|
|
307
|
-
if (
|
|
308
|
-
|
|
15
|
+
const entries = [...formData.entries()].filter((entry) => entry[1] instanceof globalThis.File);
|
|
16
|
+
if (settings?.maxFiles !== undefined && entries.length > settings.maxFiles) {
|
|
17
|
+
throw new UploadRequestError(`${settings.maxFiles} max file uploads exceeded.`, 413);
|
|
309
18
|
}
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
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) {
|
|
333
|
-
return NextResponse.json({ errors: [{ message: `${settings.maxFiles} max file uploads exceeded.` }] }, { status: 413 });
|
|
334
|
-
}
|
|
335
|
-
// Normalize operations into a keyed object for path resolution.
|
|
336
|
-
// Single: paths are "variables.file" → use the operation object directly.
|
|
337
|
-
// Batch: paths are "0.variables.file" → use indices as keys in a wrapper object.
|
|
338
|
-
let operationsRoot;
|
|
339
|
-
if (isBatch) {
|
|
340
|
-
const batchOperations = parsedOperations;
|
|
341
|
-
operationsRoot = {};
|
|
342
|
-
for (let i = 0; i < batchOperations.length; i++) {
|
|
343
|
-
const op = batchOperations[i];
|
|
344
|
-
if (!op.variables)
|
|
345
|
-
op.variables = {};
|
|
346
|
-
operationsRoot[String(i)] = op;
|
|
19
|
+
const operationsRaw = formData.get('operations');
|
|
20
|
+
const mapRaw = formData.get('map');
|
|
21
|
+
if (typeof operationsRaw !== 'string' || typeof mapRaw !== 'string' ||
|
|
22
|
+
formData.getAll('operations').length !== 1 || formData.getAll('map').length !== 1) {
|
|
23
|
+
throw new UploadRequestError('Missing, duplicate, or invalid map/operations in form data.');
|
|
24
|
+
}
|
|
25
|
+
const files = new Map();
|
|
26
|
+
for (const [field, file] of entries) {
|
|
27
|
+
if (files.has(field))
|
|
28
|
+
throw new UploadRequestError('Duplicate multipart file field.');
|
|
29
|
+
if (settings?.maxFileSize !== undefined && file.size > settings.maxFileSize) {
|
|
30
|
+
throw new UploadRequestError(`File ${file.name} size is too large.`, 413);
|
|
347
31
|
}
|
|
32
|
+
files.set(field, file);
|
|
348
33
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
singleOp.variables = {};
|
|
353
|
-
operationsRoot = singleOp;
|
|
354
|
-
}
|
|
355
|
-
// Process files and resolve Upload instances at mapped paths.
|
|
356
|
-
const fileProcessingPromises = [];
|
|
357
|
-
for (const fileKeyInMap of Object.keys(map)) {
|
|
358
|
-
const file = files[fileKeyInMap];
|
|
34
|
+
const { operations, uploads } = prepareOperations(operationsRaw, mapRaw, settings?.maxFiles);
|
|
35
|
+
await Promise.all([...uploads].map(async ([field, upload]) => {
|
|
36
|
+
const file = files.get(field);
|
|
359
37
|
if (!file) {
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
const missingUpload = new Upload();
|
|
363
|
-
missingUpload.reject(new Error('File missing in the request.'));
|
|
364
|
-
setValueAtPath(operationsRoot, filePath, missingUpload);
|
|
365
|
-
}
|
|
366
|
-
continue;
|
|
38
|
+
upload.reject(new Error('File missing in the request.'));
|
|
39
|
+
return;
|
|
367
40
|
}
|
|
368
|
-
|
|
369
|
-
|
|
41
|
+
try {
|
|
42
|
+
upload.resolve(await processUpload(file, settings?.allowedTypes));
|
|
370
43
|
}
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
.then(uploadInstance => {
|
|
374
|
-
for (const filePath of variablePaths) {
|
|
375
|
-
setValueAtPath(operationsRoot, filePath, uploadInstance);
|
|
376
|
-
}
|
|
377
|
-
})
|
|
378
|
-
.catch((error) => {
|
|
379
|
-
for (const filePath of variablePaths) {
|
|
380
|
-
const uploadError = new Upload();
|
|
381
|
-
uploadError.reject(new Error(`Failed to process file ${file.name}: ${error.message}`));
|
|
382
|
-
setValueAtPath(operationsRoot, filePath, uploadError);
|
|
383
|
-
}
|
|
384
|
-
});
|
|
385
|
-
fileProcessingPromises.push(filePromise);
|
|
386
|
-
}
|
|
387
|
-
await Promise.all(fileProcessingPromises);
|
|
388
|
-
// Execute operations and collect results.
|
|
389
|
-
if (isBatch) {
|
|
390
|
-
const results = [];
|
|
391
|
-
const sortedKeys = Object.keys(operationsRoot).sort((a, b) => Number(a) - Number(b));
|
|
392
|
-
for (const key of sortedKeys) {
|
|
393
|
-
const op = operationsRoot[key];
|
|
394
|
-
const response = await server.executeOperation({ query: op.query, variables: op.variables || {}, ...(op.operationName !== undefined && { operationName: op.operationName }) }, { contextValue: contextValueInput });
|
|
395
|
-
results.push(await collectResponse(response));
|
|
44
|
+
catch (error) {
|
|
45
|
+
upload.reject(new Error(`Failed to process file ${file.name}: ${error.message}`));
|
|
396
46
|
}
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
const operation = operationsRoot;
|
|
400
|
-
const response = await server.executeOperation({ query: operation.query, variables: operation.variables || {}, ...(operation.operationName !== undefined && { operationName: operation.operationName }) }, { contextValue: contextValueInput });
|
|
401
|
-
return NextResponse.json(await collectResponse(response));
|
|
47
|
+
}));
|
|
48
|
+
return await executeOperations(operations, contextValueInput, server);
|
|
402
49
|
}
|
|
403
50
|
catch (error) {
|
|
404
|
-
|
|
405
|
-
return NextResponse.json({ errors: [{ message: `Error processing upload: ${errorMessage}` }] }, { status: 500 });
|
|
51
|
+
return uploadErrorResponse(error);
|
|
406
52
|
}
|
|
407
53
|
}
|
package/package.json
CHANGED
|
@@ -7,18 +7,21 @@
|
|
|
7
7
|
"url": "https://github.com/lafittemehdy/graphql-upload-nextjs/issues"
|
|
8
8
|
},
|
|
9
9
|
"dependencies": {
|
|
10
|
-
"
|
|
10
|
+
"busboy": "^1.6.0",
|
|
11
|
+
"file-type": "^22.3.0",
|
|
12
|
+
"fs-capacitor": "^8.0.0",
|
|
11
13
|
"istextorbinary": "^9.5.0"
|
|
12
14
|
},
|
|
13
15
|
"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
16
|
"devDependencies": {
|
|
15
|
-
"@types/
|
|
16
|
-
"
|
|
17
|
+
"@types/busboy": "^1.5.5",
|
|
18
|
+
"@types/node": "^26.6.6",
|
|
19
|
+
"graphql": "^16.15.0",
|
|
17
20
|
"husky": "^9.1.7",
|
|
18
|
-
"next": "^16.4.
|
|
21
|
+
"next": "^16.4.5",
|
|
19
22
|
"typescript": "^7.0.2",
|
|
20
|
-
"undici": "^8.12.
|
|
21
|
-
"vitest": "^5.0
|
|
23
|
+
"undici": "^8.12.4",
|
|
24
|
+
"vitest": "^5.1.0"
|
|
22
25
|
},
|
|
23
26
|
"files": [
|
|
24
27
|
"CODE_OF_CONDUCT.md",
|
|
@@ -26,8 +29,12 @@
|
|
|
26
29
|
"LICENSE",
|
|
27
30
|
"README.md",
|
|
28
31
|
"SECURITY.md",
|
|
32
|
+
"core.d.ts",
|
|
33
|
+
"core.js",
|
|
29
34
|
"index.d.ts",
|
|
30
|
-
"index.js"
|
|
35
|
+
"index.js",
|
|
36
|
+
"streaming.d.ts",
|
|
37
|
+
"streaming.js"
|
|
31
38
|
],
|
|
32
39
|
"engines": {
|
|
33
40
|
"node": ">=22.13.0"
|
|
@@ -49,14 +56,14 @@
|
|
|
49
56
|
"main": "index.js",
|
|
50
57
|
"name": "graphql-upload-nextjs",
|
|
51
58
|
"overrides": {
|
|
52
|
-
"postcss": "8.5.
|
|
53
|
-
"@graphql-tools/utils": "13.
|
|
54
|
-
"@fastify/busboy": "3.2.
|
|
55
|
-
"qs": "6.
|
|
59
|
+
"postcss": "8.5.32",
|
|
60
|
+
"@graphql-tools/utils": "13.2.1",
|
|
61
|
+
"@fastify/busboy": "3.2.5",
|
|
62
|
+
"qs": "6.17.1",
|
|
56
63
|
"source-map-js": "1.2.2",
|
|
57
|
-
"body-parser": "2.
|
|
64
|
+
"body-parser": "2.4.0"
|
|
58
65
|
},
|
|
59
|
-
"packageManager": "npm@12.2.
|
|
66
|
+
"packageManager": "npm@12.2.2",
|
|
60
67
|
"peerDependencies": {
|
|
61
68
|
"@apollo/server": "^5.0.0",
|
|
62
69
|
"graphql": "^16.0.0",
|
|
@@ -73,12 +80,14 @@
|
|
|
73
80
|
"scripts": {
|
|
74
81
|
"build": "tsc",
|
|
75
82
|
"dev": "tsc --watch",
|
|
76
|
-
"prepublishOnly": "npm run build && npm test",
|
|
83
|
+
"prepublishOnly": "npm run build && npm test && npm run test:types",
|
|
77
84
|
"start": "tsc && node index.js",
|
|
78
85
|
"test": "vitest run",
|
|
86
|
+
"test:types": "tsc --ignoreConfig --noEmit --strict --skipLibCheck --module NodeNext --moduleResolution NodeNext --target ES2022 tests/public-api.ts",
|
|
87
|
+
"test:integration": "node --test tests/next-http.test.mjs",
|
|
79
88
|
"prepare": "husky || exit 0"
|
|
80
89
|
},
|
|
81
90
|
"type": "module",
|
|
82
91
|
"types": "index.d.ts",
|
|
83
|
-
"version": "3.
|
|
92
|
+
"version": "3.1.0"
|
|
84
93
|
}
|
package/streaming.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { NextResponse } from 'next/server.js';
|
|
2
|
+
import { Readable } from 'node:stream';
|
|
3
|
+
import { type File, type MinimalRequest, type UploadProcessSettings, type UploadServer } from './core.js';
|
|
4
|
+
/** Streaming metadata deliberately has a different size contract from the buffered File. */
|
|
5
|
+
export interface StreamingFile extends Omit<File, 'fileSize' | 'createReadStream'> {
|
|
6
|
+
/** Resolves after this file has been completely received and written to temporary storage. */
|
|
7
|
+
fileSize: Promise<number>;
|
|
8
|
+
createReadStream: () => Readable;
|
|
9
|
+
/** Cancels the entire multipart request, including any aliases and other pending uploads. */
|
|
10
|
+
abort: () => void;
|
|
11
|
+
}
|
|
12
|
+
export interface StreamingRequest {
|
|
13
|
+
body: ReadableStream<Uint8Array> | null;
|
|
14
|
+
headers: MinimalRequest['headers'];
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
}
|
|
17
|
+
export interface StreamingUploadSettings extends UploadProcessSettings {
|
|
18
|
+
maxFieldSize?: number;
|
|
19
|
+
maxRequestSize?: number;
|
|
20
|
+
}
|
|
21
|
+
/** Opt-in Node.js API; success waits for reception, and all readers must finish within execution. */
|
|
22
|
+
export declare function uploadProcessStreaming<TContext extends Record<string, unknown>>(request: StreamingRequest, contextValueInput: TContext, server: UploadServer<TContext>, settings?: StreamingUploadSettings): Promise<NextResponse>;
|