graphql-upload-nextjs 0.1.1 → 2.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 +217 -239
- package/index.d.ts +40 -26
- package/index.js +218 -112
- package/package.json +28 -18
package/README.md
CHANGED
|
@@ -1,63 +1,76 @@
|
|
|
1
1
|
# graphql-upload-nextjs
|
|
2
2
|
|
|
3
|
-
[](https://www.npmjs.com/package/graphql-upload-nextjs)
|
|
4
|
+
[](https://github.com/lafittemehdy/graphql-upload-nextjs/actions/workflows/ci.yml)
|
|
5
|
+
[](https://github.com/lafittemehdy/graphql-upload-nextjs/blob/master/LICENSE)
|
|
6
|
+
[](https://github.com/jaydenseric/graphql-multipart-request-spec)
|
|
7
|
+
[](https://nodejs.org)
|
|
8
|
+
[](https://www.typescriptlang.org)
|
|
4
9
|
|
|
5
|
-
|
|
10
|
+
A [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec) implementation for [Next.js](https://nextjs.org) App Router with [Apollo Server](https://www.apollographql.com/docs/apollo-server). Enables file uploads via GraphQL mutations using the `Upload` scalar, with built-in MIME type verification via magic bytes.
|
|
6
11
|
|
|
7
12
|
## Features
|
|
8
13
|
|
|
9
|
-
-
|
|
10
|
-
-
|
|
11
|
-
-
|
|
12
|
-
-
|
|
13
|
-
-
|
|
14
|
+
- Implements the [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec).
|
|
15
|
+
- Designed for Next.js App Router route handlers.
|
|
16
|
+
- Supports single file uploads, multiple file uploads, and operation batching.
|
|
17
|
+
- File deduplication (one file mapped to multiple operation paths).
|
|
18
|
+
- MIME type verified via magic bytes using [file-type](https://npm.im/file-type), not trusting client headers.
|
|
19
|
+
- Configurable `allowedTypes`, `maxFileSize`, and `maxFiles`.
|
|
20
|
+
- Only reads 4KB for MIME detection — streams the rest directly from `Blob`.
|
|
21
|
+
- Spec-compatible property names: `filename`, `mimetype`, `encoding`, `createReadStream`.
|
|
14
22
|
|
|
15
23
|
## Installation
|
|
16
24
|
|
|
17
|
-
To install the package, use one of the following commands:
|
|
18
|
-
|
|
19
25
|
```bash
|
|
20
26
|
npm install graphql-upload-nextjs
|
|
21
|
-
# or
|
|
22
|
-
yarn add graphql-upload-nextjs
|
|
23
|
-
# or
|
|
24
|
-
pnpm add graphql-upload-nextjs
|
|
25
27
|
```
|
|
26
28
|
|
|
27
|
-
##
|
|
29
|
+
## Migrating from graphql-upload
|
|
28
30
|
|
|
29
|
-
|
|
31
|
+
[graphql-upload](https://github.com/jaydenseric/graphql-upload) uses Express/Koa middleware that is incompatible with Next.js App Router route handlers. This package provides the same `Upload` scalar and file object interface for the Next.js environment.
|
|
30
32
|
|
|
31
|
-
|
|
33
|
+
Property names match the original: `filename`, `mimetype`, `encoding`, `createReadStream`. An additional `fileSize` property is also available.
|
|
32
34
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
+
**Before (graphql-upload with Express):**
|
|
36
|
+
```typescript
|
|
37
|
+
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs'
|
|
38
|
+
app.use(graphqlUploadExpress())
|
|
39
|
+
```
|
|
35
40
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
import {
|
|
39
|
-
import { pipeline } from 'stream'
|
|
40
|
-
import { startServerAndCreateNextHandler } from '@as-integrations/next'
|
|
41
|
+
**After (graphql-upload-nextjs with App Router):**
|
|
42
|
+
```typescript
|
|
43
|
+
import { GraphQLUpload, uploadProcess } from 'graphql-upload-nextjs'
|
|
41
44
|
|
|
42
|
-
//
|
|
43
|
-
|
|
44
|
-
|
|
45
|
+
// In your route handler:
|
|
46
|
+
if (request.headers.get("content-type")?.includes("multipart/form-data")) {
|
|
47
|
+
return await uploadProcess(request, context, server);
|
|
48
|
+
}
|
|
45
49
|
```
|
|
46
50
|
|
|
47
|
-
|
|
51
|
+
Resolver code stays the same — `filename`, `mimetype`, `encoding`, and `createReadStream` work identically.
|
|
52
|
+
|
|
53
|
+
## Usage
|
|
54
|
+
|
|
55
|
+
### Schema and Resolvers
|
|
48
56
|
|
|
49
|
-
|
|
57
|
+
```typescript
|
|
58
|
+
import path from 'node:path'
|
|
59
|
+
import { createWriteStream } from 'node:fs'
|
|
60
|
+
import { pipeline } from 'node:stream'
|
|
61
|
+
import { gql } from '@apollo/client' // Optional: syntax highlighting only.
|
|
62
|
+
import { ApolloServer } from '@apollo/server'
|
|
63
|
+
import { startServerAndCreateNextHandler } from '@as-integrations/next'
|
|
64
|
+
import { type File, GraphQLUpload, uploadProcess } from 'graphql-upload-nextjs'
|
|
65
|
+
import type { NextRequest } from 'next/server.js'
|
|
50
66
|
|
|
51
|
-
```javascript
|
|
52
|
-
// For this example, we define the GraphQL schema and resolvers below.
|
|
53
67
|
const typeDefs = gql`
|
|
54
|
-
# Custom scalar type for handling file uploads.
|
|
55
68
|
scalar Upload
|
|
56
69
|
type File {
|
|
57
70
|
encoding: String!
|
|
58
|
-
|
|
71
|
+
filename: String!
|
|
59
72
|
fileSize: Int!
|
|
60
|
-
|
|
73
|
+
mimetype: String!
|
|
61
74
|
uri: String!
|
|
62
75
|
}
|
|
63
76
|
type Query {
|
|
@@ -69,265 +82,230 @@ const typeDefs = gql`
|
|
|
69
82
|
}
|
|
70
83
|
`
|
|
71
84
|
|
|
85
|
+
interface FileResponse {
|
|
86
|
+
encoding: string;
|
|
87
|
+
filename: string;
|
|
88
|
+
fileSize: number;
|
|
89
|
+
mimetype: string;
|
|
90
|
+
uri: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
72
93
|
const resolvers = {
|
|
73
94
|
Mutation: {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
95
|
+
uploadFile: async (
|
|
96
|
+
_parent: undefined,
|
|
97
|
+
{ file }: { file: Promise<File> },
|
|
98
|
+
): Promise<FileResponse> => {
|
|
99
|
+
const { createReadStream, encoding, filename, fileSize, mimetype } = await file;
|
|
100
|
+
const safeName = path.basename(filename);
|
|
101
|
+
return new Promise((resolve, reject) => {
|
|
102
|
+
pipeline(
|
|
103
|
+
createReadStream(),
|
|
104
|
+
createWriteStream(`./uploads/${safeName}`),
|
|
105
|
+
(error) => {
|
|
106
|
+
if (error) reject(new Error("Error during file upload."));
|
|
107
|
+
else resolve({ encoding, filename: safeName, fileSize, mimetype, uri: `/${safeName}` });
|
|
108
|
+
},
|
|
109
|
+
);
|
|
110
|
+
});
|
|
111
|
+
},
|
|
112
|
+
uploadFiles: async (
|
|
113
|
+
_parent: undefined,
|
|
114
|
+
{ files }: { files: Promise<File>[] },
|
|
115
|
+
): Promise<FileResponse[]> => {
|
|
116
|
+
const resolvedFiles = await Promise.all(files);
|
|
117
|
+
return Promise.all(resolvedFiles.map(async ({ createReadStream, encoding, filename, fileSize, mimetype }) => {
|
|
118
|
+
const safeName = path.basename(filename);
|
|
119
|
+
return new Promise<FileResponse>((resolve, reject) => {
|
|
81
120
|
pipeline(
|
|
82
121
|
createReadStream(),
|
|
83
|
-
|
|
84
|
-
createWriteStream(`./public/${fileName}`),
|
|
122
|
+
createWriteStream(`./uploads/${safeName}`),
|
|
85
123
|
(error) => {
|
|
86
|
-
if (error) {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
resolve({ encoding, fileName, fileSize, mimeType, uri: `http://localhost:3000/${fileName}` })
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
)
|
|
96
|
-
})
|
|
97
|
-
} catch (error) {
|
|
98
|
-
// You should handle any errors that occur during file upload more gracefully.
|
|
99
|
-
console.error('Error handling file upload:', error)
|
|
100
|
-
throw new Error('Failed to handle file upload.')
|
|
101
|
-
}
|
|
124
|
+
if (error) reject(new Error(`Error during upload of ${safeName}.`));
|
|
125
|
+
else resolve({ encoding, filename: safeName, fileSize, mimetype, uri: `/${safeName}` });
|
|
126
|
+
},
|
|
127
|
+
);
|
|
128
|
+
});
|
|
129
|
+
}));
|
|
102
130
|
},
|
|
103
|
-
uploadFiles: async (_parent: void, { files }: { files: [Promise<File>] }, { ip }: Context) => {
|
|
104
|
-
try {
|
|
105
|
-
const results = await Promise.all(
|
|
106
|
-
files.map(async (file) => {
|
|
107
|
-
const { createReadStream, encoding, fileName, fileSize, mimeType } = await file;
|
|
108
|
-
return new Promise((resolve, reject) => {
|
|
109
|
-
pipeline(
|
|
110
|
-
createReadStream(),
|
|
111
|
-
createWriteStream(`./public/${fileName}`), // Store in 'public' for simplicity
|
|
112
|
-
(error) => {
|
|
113
|
-
if (error) {
|
|
114
|
-
console.error('File upload pipeline error:', error);
|
|
115
|
-
reject(new Error('Error during file upload.'));
|
|
116
|
-
} else {
|
|
117
|
-
console.log(`${ip} successfully uploaded ${fileName}`);
|
|
118
|
-
resolve({ encoding, fileName, fileSize, mimeType, uri: `http://localhost:3000/${fileName}` });
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
);
|
|
122
|
-
});
|
|
123
|
-
})
|
|
124
|
-
);
|
|
125
|
-
return results;
|
|
126
|
-
} catch (error) {
|
|
127
|
-
console.error('Error handling multiple file uploads:', error);
|
|
128
|
-
throw new Error('Failed to handle multiple file uploads.');
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
},
|
|
132
|
-
Query: {
|
|
133
|
-
default: async () => true
|
|
134
131
|
},
|
|
135
|
-
|
|
136
|
-
Upload: GraphQLUpload
|
|
132
|
+
Query: { default: async () => true },
|
|
133
|
+
Upload: GraphQLUpload,
|
|
137
134
|
}
|
|
138
135
|
```
|
|
139
136
|
|
|
140
|
-
|
|
137
|
+
> **Security:** Always sanitize filenames with `path.basename()` to prevent path traversal attacks. Never write uploaded files to publicly accessible directories in production.
|
|
141
138
|
|
|
142
|
-
|
|
139
|
+
### Route Handler
|
|
143
140
|
|
|
144
|
-
```
|
|
145
|
-
|
|
146
|
-
const server = new ApolloServer({ resolvers, typeDefs })
|
|
141
|
+
```typescript
|
|
142
|
+
const server = new ApolloServer({ resolvers, typeDefs });
|
|
147
143
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
// We centralize the context creation to avoid code duplication.
|
|
155
|
-
const contextHandler = async (req: NextRequest, authenticated: string | boolean = false): Promise<Context> => {
|
|
156
|
-
const ip = req.ip || req.headers.get('x-forwarded-for') || ''
|
|
157
|
-
// Since we've already authenticated the user, we skip it here. See the requestHandler for more details.
|
|
158
|
-
if (authenticated) return { ip, req }
|
|
159
|
-
// Default context for normal operations.
|
|
160
|
-
return { ip, req }
|
|
161
|
-
}
|
|
144
|
+
const handler = startServerAndCreateNextHandler<NextRequest>(server, {
|
|
145
|
+
context: async (req: NextRequest) => ({
|
|
146
|
+
ip: req.headers.get("x-forwarded-for") || "",
|
|
147
|
+
req,
|
|
148
|
+
}),
|
|
149
|
+
});
|
|
162
150
|
|
|
163
|
-
// Apollo, we have liftoff! 🚀
|
|
164
|
-
const handler = startServerAndCreateNextHandler<NextRequest, Context>(server, { context: contextHandler })
|
|
165
|
-
|
|
166
|
-
// Handle upload requests separately from other GraphQL operations.
|
|
167
|
-
// Note: This implementation is basic and needs enhancement for production use.
|
|
168
151
|
const requestHandler = async (request: NextRequest) => {
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
// Authenticate before uploading to prevent abuse.
|
|
173
|
-
// Pass the authenticated user to contextHandler to skip redundant authentication.
|
|
174
|
-
// 'User' is used as a placeholder for the authenticated user.
|
|
175
|
-
const context = await contextHandler(request, 'User')
|
|
176
|
-
return await uploadProcess(
|
|
177
|
-
request,
|
|
178
|
-
context,
|
|
179
|
-
server,
|
|
180
|
-
{
|
|
181
|
-
// Allow only certain MIME types
|
|
182
|
-
allowedTypes: ['image/jpeg', 'image/png', 'text/plain'],
|
|
183
|
-
// Only allow image uploads up to 10MB.
|
|
184
|
-
maxFileSize: 10 * 1024 * 1024
|
|
185
|
-
}
|
|
186
|
-
)
|
|
187
|
-
}
|
|
188
|
-
// Handle all other requests with the Apollo Server.
|
|
189
|
-
return handler(request)
|
|
190
|
-
} catch (error) {
|
|
191
|
-
// In a production environment, errors should be handled more gracefully.
|
|
192
|
-
console.error('Error in request handling:', error)
|
|
193
|
-
throw new Error('Failed to process request.')
|
|
152
|
+
if (request.headers.get("content-type")?.includes("multipart/form-data")) {
|
|
153
|
+
const context = { ip: request.headers.get("x-forwarded-for") || "", req: request };
|
|
154
|
+
return await uploadProcess(request, context, server);
|
|
194
155
|
}
|
|
195
|
-
|
|
156
|
+
return handler(request);
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
export const GET = requestHandler;
|
|
160
|
+
export const POST = requestHandler;
|
|
161
|
+
export const OPTIONS = requestHandler;
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
### Configuration
|
|
196
165
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
166
|
+
```typescript
|
|
167
|
+
await uploadProcess(request, context, server, {
|
|
168
|
+
allowedTypes: ["image/jpeg", "image/png", "text/plain"],
|
|
169
|
+
maxFiles: 10,
|
|
170
|
+
maxFileSize: 10 * 1024 * 1024, // 10MB
|
|
171
|
+
});
|
|
201
172
|
```
|
|
202
173
|
|
|
203
|
-
|
|
174
|
+
| Option | Type | Default | Description |
|
|
175
|
+
|---|---|---|---|
|
|
176
|
+
| `allowedTypes` | `string[]` | `undefined` | Restrict MIME types. Verified via magic bytes. |
|
|
177
|
+
| `maxFiles` | `number` | `undefined` | Max files per request. Returns 413 if exceeded. |
|
|
178
|
+
| `maxFileSize` | `number` | `undefined` | Max file size in bytes. Returns 413 if exceeded. |
|
|
179
|
+
|
|
180
|
+
### Client Usage
|
|
204
181
|
|
|
205
|
-
When
|
|
182
|
+
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.
|
|
206
183
|
|
|
207
|
-
|
|
184
|
+
```typescript
|
|
185
|
+
import { gql, useMutation } from '@apollo/client';
|
|
208
186
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
uploadFile(file: $file) {
|
|
213
|
-
fileName
|
|
214
|
-
mimeType
|
|
215
|
-
encoding
|
|
216
|
-
uri
|
|
217
|
-
fileSize
|
|
187
|
+
const UPLOAD = gql`
|
|
188
|
+
mutation UploadFile($file: Upload!) {
|
|
189
|
+
uploadFile(file: $file) { filename mimetype fileSize }
|
|
218
190
|
}
|
|
191
|
+
`;
|
|
192
|
+
|
|
193
|
+
function Uploader() {
|
|
194
|
+
const [upload] = useMutation(UPLOAD);
|
|
195
|
+
return <input type="file" onChange={(e) => {
|
|
196
|
+
const file = e.target.files?.[0];
|
|
197
|
+
if (file) upload({ variables: { file } });
|
|
198
|
+
}} />;
|
|
219
199
|
}
|
|
220
200
|
```
|
|
221
201
|
|
|
222
|
-
|
|
223
|
-
The key in the variables object (`"file"`) must match the argument name in your GraphQL mutation (`$file`).
|
|
224
|
-
When using a GraphQL client library (e.g., Apollo Client, urql, Relay):
|
|
225
|
-
* You'll typically pass the browser's `File` object (e.g., from an `<input type="file">`) directly as the value for the `file` variable.
|
|
226
|
-
* The client library automatically constructs the multipart/form-data request according to the GraphQL multipart request specification.
|
|
202
|
+
## API Reference
|
|
227
203
|
|
|
228
|
-
|
|
204
|
+
### Core Exports
|
|
229
205
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
206
|
+
| Export | Type | Description |
|
|
207
|
+
|---|---|---|
|
|
208
|
+
| `GraphQLUpload` | `GraphQLScalarType` | The `Upload` scalar for your GraphQL schema. |
|
|
209
|
+
| `uploadProcess` | `function` | Processes a multipart request with file uploads. |
|
|
210
|
+
| `Upload` | `class` | Holds a promise that resolves with file upload details. |
|
|
234
211
|
|
|
235
|
-
|
|
236
|
-
mutation UploadFile($file: Upload!) {
|
|
237
|
-
uploadFile(file: $file) { fileName }
|
|
238
|
-
}
|
|
239
|
-
`;
|
|
212
|
+
### File Object
|
|
240
213
|
|
|
241
|
-
|
|
242
|
-
const [uploadFileMutation] = useMutation(UPLOAD_FILE_MUTATION);
|
|
214
|
+
The resolved file object passed to resolvers:
|
|
243
215
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
216
|
+
| Property | Type | Description |
|
|
217
|
+
|---|---|---|
|
|
218
|
+
| `createReadStream` | `() => ReadableStream` | Creates a Node.js readable stream of the file contents. Replayable. |
|
|
219
|
+
| `encoding` | `string` | Transfer encoding (always `'binary'` with FormData API). |
|
|
220
|
+
| `filename` | `string` | Original file name from the client. |
|
|
221
|
+
| `fileSize` | `number` | File size in bytes. |
|
|
222
|
+
| `mimetype` | `string` | MIME type verified via magic bytes. |
|
|
250
223
|
|
|
251
|
-
|
|
252
|
-
}
|
|
253
|
-
```
|
|
224
|
+
### Utility Exports
|
|
254
225
|
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
encoding
|
|
264
|
-
uri
|
|
265
|
-
fileSize
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
```
|
|
226
|
+
| Export | Type | Description |
|
|
227
|
+
|---|---|---|
|
|
228
|
+
| `bufferToStream` | `(buffer: Buffer) => ReadableStream` | Converts a Buffer to a Node.js readable stream. |
|
|
229
|
+
| `parseOperationsJSON` | `(input: string) => object \| object[]` | Parses the operations field (object or array for batching). |
|
|
230
|
+
| `sanitizeAndValidateJSON` | `(input: string) => object` | Parses JSON and validates it's a non-null, non-array object. |
|
|
231
|
+
| `setValueAtPath` | `(obj, path, value) => void` | Sets a value at a dot-notation path in a nested object. |
|
|
232
|
+
| `streamToBuffer` | `(stream: ReadableStream) => Promise<Buffer>` | Collects a readable stream into a Buffer. |
|
|
233
|
+
| `validateMap` | `(map: object) => string \| null` | Validates map entries are arrays of string paths. Returns error or null. |
|
|
269
234
|
|
|
270
|
-
|
|
271
|
-
Similarly, the key `"files"` must match the argument name (`$files`).
|
|
272
|
-
When using a GraphQL client library:
|
|
273
|
-
* You'll pass an array of `File` objects as the value for the `files` variable.
|
|
274
|
-
* The client library handles the multipart request construction.
|
|
235
|
+
### TypeScript Interfaces
|
|
275
236
|
|
|
276
|
-
|
|
237
|
+
| Export | Description |
|
|
238
|
+
|---|---|
|
|
239
|
+
| `File` | Resolved file object with `filename`, `mimetype`, `encoding`, `fileSize`, `createReadStream`. |
|
|
240
|
+
| `FileStream` | FormData file entry with a `stream()` method. |
|
|
241
|
+
| `FormDataFile` | Raw file entry from multipart FormData. |
|
|
242
|
+
| `MinimalRequest` | Request interface compatible with Next.js and Web API. |
|
|
277
243
|
|
|
278
|
-
|
|
279
|
-
```javascript
|
|
280
|
-
// In your frontend code
|
|
281
|
-
const UPLOAD_FILES_MUTATION = gql`
|
|
282
|
-
mutation UploadFiles($files: [Upload!]!) {
|
|
283
|
-
uploadFiles(files: $files) { fileName }
|
|
284
|
-
}
|
|
285
|
-
`;
|
|
244
|
+
## Spec Compliance
|
|
286
245
|
|
|
287
|
-
|
|
288
|
-
const [uploadFilesMutation] = useMutation(UPLOAD_FILES_MUTATION);
|
|
246
|
+
Implements the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec) by [jaydenseric](https://github.com/jaydenseric).
|
|
289
247
|
|
|
290
|
-
|
|
291
|
-
const files = Array.from(event.target.files);
|
|
292
|
-
if (files.length > 0) {
|
|
293
|
-
uploadFilesMutation({ variables: { files } });
|
|
294
|
-
}
|
|
295
|
-
};
|
|
248
|
+
The spec defines a [multipart form field structure](https://github.com/jaydenseric/graphql-multipart-request-spec#multipart-form-field-structure) with three ordered fields (`operations`, `map`, file fields) and enables nesting files anywhere within operations, operation batching, file deduplication, and file upload streams in resolvers.
|
|
296
249
|
|
|
297
|
-
|
|
298
|
-
}
|
|
299
|
-
```
|
|
250
|
+
### Supported Capabilities
|
|
300
251
|
|
|
301
|
-
|
|
252
|
+
| Spec Capability | Status | Details |
|
|
253
|
+
|---|---|---|
|
|
254
|
+
| `operations` field ([JSON-encoded GraphQL operation](https://github.com/jaydenseric/graphql-multipart-request-spec#multipart-form-field-structure)) | Supported | Parsed and validated as object or array. |
|
|
255
|
+
| `map` field ([file-to-path mapping](https://github.com/jaydenseric/graphql-multipart-request-spec#multipart-form-field-structure)) | Supported | Validated: each entry must be an array of string paths. |
|
|
256
|
+
| [Single file upload](https://github.com/jaydenseric/graphql-multipart-request-spec#single-file) | Supported | File mapped via `"variables.file"` path. |
|
|
257
|
+
| [File list upload](https://github.com/jaydenseric/graphql-multipart-request-spec#file-list) | Supported | Files mapped via `"variables.files.0"`, `"variables.files.1"`, etc. |
|
|
258
|
+
| [Batching](https://github.com/jaydenseric/graphql-multipart-request-spec#batching) | Supported | Operations as array, paths prefixed with operation index (`"0.variables.file"`). |
|
|
259
|
+
| File deduplication | Supported | One file field mapped to multiple operation paths. |
|
|
260
|
+
| [`object-path`](https://npm.im/object-path) dot-notation | Supported | Handles nested objects and array indices. |
|
|
261
|
+
| File upload streams in resolvers | Supported | `createReadStream()` returns a Node.js readable stream. |
|
|
262
|
+
| Missing file → rejected promise | Supported | Upload promise rejected with `"File missing in the request."` |
|
|
263
|
+
| `maxFiles` / `maxFileSize` limits | Supported | Returns HTTP 413 when exceeded. |
|
|
302
264
|
|
|
303
|
-
|
|
265
|
+
### Additions Beyond the Spec
|
|
304
266
|
|
|
305
|
-
|
|
267
|
+
| Feature | Description |
|
|
268
|
+
|---|---|
|
|
269
|
+
| MIME magic byte verification | Real file type detected via [file-type](https://npm.im/file-type), not trusting client-provided `Content-Type`. |
|
|
270
|
+
| `allowedTypes` filtering | Server-side restriction of accepted MIME types. |
|
|
271
|
+
| `fileSize` property | File size in bytes available on the resolved file object. |
|
|
306
272
|
|
|
307
|
-
|
|
273
|
+
### Limitations
|
|
308
274
|
|
|
309
|
-
|
|
310
|
-
import { GraphQLUpload, type File, uploadProcess } from '../../../../../../index'
|
|
311
|
-
```
|
|
275
|
+
These are inherent trade-offs of using the Web `FormData` API for Next.js App Router compatibility. They do not affect normal spec usage.
|
|
312
276
|
|
|
313
|
-
|
|
277
|
+
| Limitation | Reason |
|
|
278
|
+
|---|---|
|
|
279
|
+
| **No field ordering validation** | The [spec requires](https://github.com/jaydenseric/graphql-multipart-request-spec#multipart-form-field-structure) `operations` → `map` → files ordering. The Web `FormData` API retrieves fields by name (`formData.get('operations')`), not by position, so ordering cannot be validated. In practice, all major client libraries ([apollo-upload-client](https://npm.im/apollo-upload-client), [extract-files](https://npm.im/extract-files)) send fields in the correct order. |
|
|
280
|
+
| **No `maxFieldSize`** | The original [graphql-upload](https://github.com/jaydenseric/graphql-upload) limits non-file field sizes via `busboy`. Next.js parses the full request body into `FormData` before our code runs, so field size limiting is not possible at this layer. |
|
|
281
|
+
| **`encoding` is always `'binary'`** | `FormData` does not expose the transfer encoding of file parts. The original `graphql-upload` reads this from `busboy`'s stream events. In practice, transfer encoding is rarely used by resolvers. |
|
|
282
|
+
| **No mid-stream abort** | The original uses `fs-capacitor` to buffer uploads to disk, allowing resolvers to abort an in-progress upload. With `FormData`, the entire request body is already parsed by the runtime. However, resolvers can still choose not to call `createReadStream()` to skip processing. |
|
|
283
|
+
| **`Blob.stream()` instead of `busboy` streaming** | Next.js route handlers receive a `Request` object (Web API), not a Node.js `IncomingMessage`. There is no access to the raw request stream. `Blob.stream()` provides a replayable readable stream per file. |
|
|
314
284
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
285
|
+
## Example
|
|
286
|
+
|
|
287
|
+
A full example project is available at [`examples/example-graphql-upload-nextjs/`](examples/example-graphql-upload-nextjs/).
|
|
318
288
|
|
|
319
289
|
## Contributing
|
|
320
290
|
|
|
321
|
-
Contributions are welcome!
|
|
291
|
+
Contributions are welcome! To get started:
|
|
292
|
+
|
|
293
|
+
```bash
|
|
294
|
+
git clone https://github.com/lafittemehdy/graphql-upload-nextjs.git
|
|
295
|
+
cd graphql-upload-nextjs
|
|
296
|
+
npm install
|
|
297
|
+
npm run build
|
|
298
|
+
npm test
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
CI runs automatically on push and pull requests via GitHub Actions (build + test on Node.js 22/24, example build + lint).
|
|
322
302
|
|
|
323
303
|
## License
|
|
324
304
|
|
|
325
|
-
|
|
305
|
+
MIT. See [LICENSE](https://github.com/lafittemehdy/graphql-upload-nextjs/blob/master/LICENSE).
|
|
326
306
|
|
|
327
307
|
## Acknowledgements
|
|
328
308
|
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
While this project deviates from the official specifications to prioritize compatibility with Next.js routes, I am committed to refining it further to align with those specifications as closely as possible. Notable enhancements include built-in security features, such as file type verification, as well as support and an example for GraphQL authentication.
|
|
309
|
+
Sincere gratitude to [jaydenseric](https://github.com/jaydenseric) for the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec) and [graphql-upload](https://github.com/jaydenseric/graphql-upload), and to [meabed](https://github.com/meabed) for [graphql-upload-ts](https://github.com/meabed/graphql-upload-ts) which served as a valuable reference.
|
|
332
310
|
|
|
333
|
-
Finally,
|
|
311
|
+
Finally, heartfelt gratitude to my mom for her unwavering support, which has allowed me to dedicate my time to working on open-source software.
|
package/index.d.ts
CHANGED
|
@@ -1,22 +1,37 @@
|
|
|
1
|
-
import { GraphQLScalarType, GraphQLError } from 'graphql';
|
|
2
|
-
import { NextResponse } from 'next/server.js';
|
|
3
1
|
import type { GraphQLResponse } from '@apollo/server';
|
|
2
|
+
import { GraphQLScalarType } from 'graphql';
|
|
3
|
+
import { NextResponse } from 'next/server.js';
|
|
4
|
+
/** Represents a processed file with metadata and stream access. */
|
|
4
5
|
export interface File {
|
|
5
6
|
createReadStream: () => NodeJS.ReadableStream;
|
|
6
7
|
encoding: string;
|
|
7
|
-
fileName: string;
|
|
8
8
|
fileSize: number;
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
export interface FileStream extends FormDataFile {
|
|
12
|
-
stream: () => Promise<NodeJS.ReadableStream>;
|
|
9
|
+
filename: string;
|
|
10
|
+
mimetype: string;
|
|
13
11
|
}
|
|
12
|
+
/** Raw file entry extracted from multipart FormData. */
|
|
14
13
|
export interface FormDataFile {
|
|
15
14
|
lastModified: number;
|
|
16
15
|
name: string;
|
|
17
16
|
size: number;
|
|
18
17
|
type: string;
|
|
19
18
|
}
|
|
19
|
+
/** Extends FormDataFile with a stream method for reading file contents. */
|
|
20
|
+
export interface FileStream extends FormDataFile {
|
|
21
|
+
stream: () => ReadableStream;
|
|
22
|
+
}
|
|
23
|
+
/** Minimal request interface compatible with Next.js and Web API requests. */
|
|
24
|
+
export interface MinimalRequest {
|
|
25
|
+
formData: () => Promise<FormData>;
|
|
26
|
+
headers: {
|
|
27
|
+
get: (name: string) => string | null;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** Parameters for Apollo Server's executeOperation method. */
|
|
31
|
+
interface ServerExecuteOperationParams {
|
|
32
|
+
query: string;
|
|
33
|
+
variables: Record<string, unknown>;
|
|
34
|
+
}
|
|
20
35
|
/**
|
|
21
36
|
* Represents an instance of a file upload.
|
|
22
37
|
* Holds a promise that resolves with the file details once processed.
|
|
@@ -28,29 +43,28 @@ export declare class Upload {
|
|
|
28
43
|
resolve: (file: File) => void;
|
|
29
44
|
constructor();
|
|
30
45
|
}
|
|
31
|
-
|
|
32
|
-
export declare
|
|
46
|
+
/** Custom GraphQL scalar type for handling file uploads. */
|
|
47
|
+
export declare const GraphQLUpload: GraphQLScalarType<Promise<File>, never>;
|
|
48
|
+
/** Converts a Buffer into a Node.js readable stream. */
|
|
33
49
|
export declare function bufferToStream(buffer: Buffer): NodeJS.ReadableStream;
|
|
50
|
+
/** Parses JSON for the operations field. Accepts objects or arrays (for batching per spec). */
|
|
51
|
+
export declare function parseOperationsJSON(input: string): Record<string, unknown> | Record<string, unknown>[];
|
|
52
|
+
/** Parses and validates a JSON string, ensuring it resolves to a non-null object (rejects arrays). */
|
|
34
53
|
export declare function sanitizeAndValidateJSON(input: string): unknown;
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
get: (name: string) => string | null;
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Processes a GraphQL multipart request with file uploads.
|
|
47
|
-
*/
|
|
54
|
+
/** Sets a value at a dot-notation path in a nested object, creating intermediate containers as needed. */
|
|
55
|
+
export declare function setValueAtPath(obj: Record<string, unknown>, path: string, value: unknown): void;
|
|
56
|
+
/** Converts a Node.js readable stream into a Buffer by collecting all chunks. */
|
|
57
|
+
export declare function streamToBuffer(stream: NodeJS.ReadableStream): Promise<Buffer>;
|
|
58
|
+
/** Validates that each map entry is an array of string paths. */
|
|
59
|
+
export declare function validateMap(map: Record<string, unknown>): string | null;
|
|
60
|
+
/** Processes a GraphQL multipart request with file uploads. Supports batching per the spec. */
|
|
48
61
|
export declare function uploadProcess<TContext extends Record<string, unknown>>(request: MinimalRequest, contextValueInput: TContext, server: {
|
|
49
62
|
executeOperation: (params: ServerExecuteOperationParams, context: {
|
|
50
63
|
contextValue: TContext;
|
|
51
64
|
}) => Promise<GraphQLResponse<TContext>>;
|
|
52
|
-
}, settings
|
|
53
|
-
allowedTypes
|
|
54
|
-
|
|
55
|
-
|
|
65
|
+
}, settings?: {
|
|
66
|
+
allowedTypes?: string[];
|
|
67
|
+
maxFiles?: number;
|
|
68
|
+
maxFileSize?: number;
|
|
69
|
+
}): Promise<NextResponse>;
|
|
56
70
|
export {};
|
package/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { GraphQLScalarType, GraphQLError } from 'graphql';
|
|
2
|
-
import { NextResponse } from 'next/server.js';
|
|
3
1
|
import { fileTypeFromBuffer } from 'file-type';
|
|
2
|
+
import { GraphQLError, GraphQLScalarType } from 'graphql';
|
|
4
3
|
import { isText } from 'istextorbinary';
|
|
4
|
+
import { NextResponse } from 'next/server.js';
|
|
5
|
+
import { Readable } from 'stream';
|
|
5
6
|
/**
|
|
6
7
|
* Represents an instance of a file upload.
|
|
7
8
|
* Holds a promise that resolves with the file details once processed.
|
|
@@ -22,176 +23,281 @@ export class Upload {
|
|
|
22
23
|
this.promise.catch(() => { });
|
|
23
24
|
}
|
|
24
25
|
}
|
|
26
|
+
/** Custom GraphQL scalar type for handling file uploads. */
|
|
25
27
|
export const GraphQLUpload = new GraphQLScalarType({
|
|
26
28
|
description: 'The Upload scalar type represents a file upload.',
|
|
27
29
|
name: 'Upload',
|
|
28
|
-
parseLiteral(node) {
|
|
29
|
-
|
|
30
|
-
|
|
30
|
+
parseLiteral(node) {
|
|
31
|
+
throw new GraphQLError('Upload literal unsupported.', { nodes: node });
|
|
32
|
+
},
|
|
33
|
+
parseValue(value) {
|
|
34
|
+
if (value instanceof Upload)
|
|
35
|
+
return value.promise;
|
|
36
|
+
throw new GraphQLError('Upload value invalid.');
|
|
37
|
+
},
|
|
38
|
+
serialize() {
|
|
39
|
+
throw new GraphQLError('Upload serialization unsupported.');
|
|
40
|
+
},
|
|
31
41
|
});
|
|
42
|
+
/** Converts a Buffer into a Node.js readable stream. */
|
|
43
|
+
export function bufferToStream(buffer) {
|
|
44
|
+
const stream = new Readable();
|
|
45
|
+
stream.push(buffer);
|
|
46
|
+
stream.push(null);
|
|
47
|
+
return stream;
|
|
48
|
+
}
|
|
49
|
+
/** Collects a GraphQL response into a serializable result object. */
|
|
50
|
+
async function collectResponse(response) {
|
|
51
|
+
if (response.body.kind === 'single') {
|
|
52
|
+
return response.body.singleResult;
|
|
53
|
+
}
|
|
54
|
+
if (response.body.kind === 'incremental') {
|
|
55
|
+
const { initialResult, subsequentResults } = response.body;
|
|
56
|
+
const collected = [];
|
|
57
|
+
for await (const result of subsequentResults) {
|
|
58
|
+
collected.push(result);
|
|
59
|
+
}
|
|
60
|
+
return { initialResult, subsequentResults: collected };
|
|
61
|
+
}
|
|
62
|
+
return { errors: [{ message: 'Unexpected server response format' }] };
|
|
63
|
+
}
|
|
64
|
+
/** Extracts File entries from multipart FormData. */
|
|
32
65
|
async function extractFiles(formData) {
|
|
33
66
|
const files = {};
|
|
34
|
-
for (const [key, value] of
|
|
67
|
+
for (const [key, value] of formData.entries()) {
|
|
35
68
|
if (value instanceof globalThis.File) {
|
|
36
69
|
files[key] = value;
|
|
37
70
|
}
|
|
38
71
|
}
|
|
39
72
|
return files;
|
|
40
73
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
74
|
+
/** Parses JSON for the operations field. Accepts objects or arrays (for batching per spec). */
|
|
75
|
+
export function parseOperationsJSON(input) {
|
|
76
|
+
let result;
|
|
77
|
+
try {
|
|
78
|
+
result = JSON.parse(input);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
throw new Error('Invalid JSON in the operations multipart field.');
|
|
82
|
+
}
|
|
83
|
+
if (typeof result !== 'object' || result === null) {
|
|
84
|
+
throw new Error('Invalid type for the operations multipart field.');
|
|
85
|
+
}
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Processes a file from FormData, detects its MIME type via magic bytes,
|
|
90
|
+
* and returns a resolved Upload instance with streaming file access.
|
|
91
|
+
*/
|
|
92
|
+
async function processUpload(file, allowedTypes) {
|
|
93
|
+
if (!file.name || typeof file.size !== 'number' || !file.type) {
|
|
94
|
+
throw new Error('Invalid file properties: name, size, or type is missing or invalid.');
|
|
95
|
+
}
|
|
96
|
+
const blob = file;
|
|
97
|
+
// Only read the first 4100 bytes for MIME type detection via magic bytes.
|
|
98
|
+
// This avoids buffering the entire file into memory.
|
|
99
|
+
const DETECTION_BYTES = 4100;
|
|
100
|
+
const headerBuffer = Buffer.from(await blob.slice(0, DETECTION_BYTES).arrayBuffer());
|
|
101
|
+
const fileTypeInfo = await fileTypeFromBuffer(new Uint8Array(headerBuffer.buffer, headerBuffer.byteOffset, headerBuffer.byteLength));
|
|
102
|
+
let mimetype = file.type;
|
|
103
|
+
if (fileTypeInfo) {
|
|
104
|
+
mimetype = fileTypeInfo.mime;
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
try {
|
|
108
|
+
if (await isText(file.name, headerBuffer)) {
|
|
109
|
+
mimetype = 'text/plain';
|
|
110
|
+
}
|
|
49
111
|
}
|
|
50
|
-
|
|
51
|
-
|
|
112
|
+
catch {
|
|
113
|
+
// Fallback: isText detection failed, proceeding with original mimetype from FormData.
|
|
52
114
|
}
|
|
53
115
|
}
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
116
|
+
if (allowedTypes && !allowedTypes.includes(mimetype)) {
|
|
117
|
+
throw new Error(`File type ${mimetype} is not allowed. Allowed types: ${allowedTypes.join(', ')}`);
|
|
118
|
+
}
|
|
119
|
+
const upload = new Upload();
|
|
120
|
+
upload.resolve({
|
|
121
|
+
createReadStream: () => Readable.fromWeb(blob.stream()),
|
|
122
|
+
encoding: 'binary',
|
|
123
|
+
fileSize: file.size,
|
|
124
|
+
filename: file.name,
|
|
125
|
+
mimetype,
|
|
126
|
+
});
|
|
127
|
+
return upload;
|
|
62
128
|
}
|
|
129
|
+
/** Parses and validates a JSON string, ensuring it resolves to a non-null object (rejects arrays). */
|
|
63
130
|
export function sanitizeAndValidateJSON(input) {
|
|
131
|
+
let result;
|
|
64
132
|
try {
|
|
65
|
-
|
|
66
|
-
if (typeof result !== 'object' || result === null) {
|
|
67
|
-
throw new Error('Invalid JSON structure: not an object.');
|
|
68
|
-
}
|
|
69
|
-
return result;
|
|
133
|
+
result = JSON.parse(input);
|
|
70
134
|
}
|
|
71
135
|
catch (error) {
|
|
72
136
|
throw new Error(`Invalid JSON input: ${error.message}`);
|
|
73
137
|
}
|
|
138
|
+
if (typeof result !== 'object' || result === null || Array.isArray(result)) {
|
|
139
|
+
throw new Error('Invalid JSON structure: expected a non-null object.');
|
|
140
|
+
}
|
|
141
|
+
return result;
|
|
74
142
|
}
|
|
75
|
-
|
|
143
|
+
/** Dangerous property names that could lead to prototype pollution. */
|
|
144
|
+
const BLOCKED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
145
|
+
/** Sets a value at a dot-notation path in a nested object, creating intermediate containers as needed. */
|
|
146
|
+
export function setValueAtPath(obj, path, value) {
|
|
76
147
|
const keys = path.split('.');
|
|
77
148
|
let current = obj;
|
|
78
149
|
for (let i = 0; i < keys.length - 1; i++) {
|
|
79
150
|
const key = keys[i];
|
|
151
|
+
if (BLOCKED_KEYS.has(key)) {
|
|
152
|
+
throw new Error(`Invalid path segment: '${key}' is not allowed.`);
|
|
153
|
+
}
|
|
80
154
|
const nextKeyIsArrayIndex = /^\d+$/.test(keys[i + 1]);
|
|
81
|
-
if (!current[key] ||
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
155
|
+
if (!current[key] ||
|
|
156
|
+
typeof current[key] !== 'object' ||
|
|
157
|
+
(nextKeyIsArrayIndex && !Array.isArray(current[key])) ||
|
|
158
|
+
(!nextKeyIsArrayIndex && Array.isArray(current[key]))) {
|
|
85
159
|
current[key] = nextKeyIsArrayIndex ? [] : {};
|
|
86
160
|
}
|
|
87
161
|
current = current[key];
|
|
88
162
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
if (!file.name || typeof file.size !== 'number' || !file.type) {
|
|
93
|
-
throw new Error('Invalid file properties: name, size, or type is missing or invalid.');
|
|
94
|
-
}
|
|
95
|
-
const stream = await file.stream();
|
|
96
|
-
const buffer = await streamToBuffer(stream);
|
|
97
|
-
const uint8ArrayForFileType = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
98
|
-
const fileTypeInfo = await fileTypeFromBuffer(uint8ArrayForFileType);
|
|
99
|
-
let mimeType = file.type;
|
|
100
|
-
if (fileTypeInfo) {
|
|
101
|
-
mimeType = fileTypeInfo.mime;
|
|
163
|
+
const finalKey = keys[keys.length - 1];
|
|
164
|
+
if (BLOCKED_KEYS.has(finalKey)) {
|
|
165
|
+
throw new Error(`Invalid path segment: '${finalKey}' is not allowed.`);
|
|
102
166
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
167
|
+
current[finalKey] = value;
|
|
168
|
+
}
|
|
169
|
+
/** Converts a Node.js readable stream into a Buffer by collecting all chunks. */
|
|
170
|
+
export async function streamToBuffer(stream) {
|
|
171
|
+
const chunks = [];
|
|
172
|
+
for await (const chunk of stream) {
|
|
173
|
+
if (Buffer.isBuffer(chunk)) {
|
|
174
|
+
chunks.push(chunk);
|
|
109
175
|
}
|
|
110
|
-
|
|
111
|
-
|
|
176
|
+
else if (typeof chunk === 'string') {
|
|
177
|
+
chunks.push(Buffer.from(chunk));
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
chunks.push(Buffer.from(chunk));
|
|
112
181
|
}
|
|
113
182
|
}
|
|
114
|
-
|
|
115
|
-
|
|
183
|
+
return Buffer.concat(chunks);
|
|
184
|
+
}
|
|
185
|
+
/** Validates that each map entry is an array of string paths. */
|
|
186
|
+
export function validateMap(map) {
|
|
187
|
+
for (const [key, paths] of Object.entries(map)) {
|
|
188
|
+
if (!Array.isArray(paths)) {
|
|
189
|
+
return `Invalid type for map entry '${key}': expected an array of paths.`;
|
|
190
|
+
}
|
|
191
|
+
for (const p of paths) {
|
|
192
|
+
if (typeof p !== 'string') {
|
|
193
|
+
return `Invalid path in map entry '${key}': expected string.`;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
116
196
|
}
|
|
117
|
-
|
|
118
|
-
upload.resolve({
|
|
119
|
-
fileSize: file.size,
|
|
120
|
-
fileName: file.name,
|
|
121
|
-
mimeType: mimeType,
|
|
122
|
-
encoding: 'binary',
|
|
123
|
-
createReadStream: () => bufferToStream(buffer)
|
|
124
|
-
});
|
|
125
|
-
return upload;
|
|
197
|
+
return null;
|
|
126
198
|
}
|
|
127
|
-
/**
|
|
128
|
-
* Processes a GraphQL multipart request with file uploads.
|
|
129
|
-
*/
|
|
199
|
+
/** Processes a GraphQL multipart request with file uploads. Supports batching per the spec. */
|
|
130
200
|
export async function uploadProcess(request, contextValueInput, server, settings) {
|
|
131
201
|
try {
|
|
132
202
|
const formData = await request.formData();
|
|
133
203
|
const files = await extractFiles(formData);
|
|
134
|
-
const
|
|
135
|
-
const
|
|
136
|
-
if (!
|
|
137
|
-
|
|
204
|
+
const mapRaw = formData.get('map');
|
|
205
|
+
const operationsRaw = formData.get('operations');
|
|
206
|
+
if (!mapRaw || !operationsRaw || typeof mapRaw !== 'string' || typeof operationsRaw !== 'string') {
|
|
207
|
+
return NextResponse.json({ errors: [{ message: 'Missing or invalid map/operations in form data.' }] }, { status: 400 });
|
|
138
208
|
}
|
|
139
|
-
const
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
209
|
+
const mapString = mapRaw;
|
|
210
|
+
const operationsString = operationsRaw;
|
|
211
|
+
// Parse and validate the map field (must be an object, not array).
|
|
212
|
+
let map;
|
|
213
|
+
try {
|
|
214
|
+
map = sanitizeAndValidateJSON(mapString);
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return NextResponse.json({ errors: [{ message: 'Invalid JSON in the map multipart field.' }] }, { status: 400 });
|
|
218
|
+
}
|
|
219
|
+
const mapError = validateMap(map);
|
|
220
|
+
if (mapError) {
|
|
221
|
+
return NextResponse.json({ errors: [{ message: mapError }] }, { status: 400 });
|
|
222
|
+
}
|
|
223
|
+
// Parse the operations field (object or array for batching).
|
|
224
|
+
let parsedOperations;
|
|
225
|
+
try {
|
|
226
|
+
parsedOperations = parseOperationsJSON(operationsString);
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
return NextResponse.json({ errors: [{ message: 'Invalid JSON in the operations multipart field.' }] }, { status: 400 });
|
|
230
|
+
}
|
|
231
|
+
// Check maxFiles limit.
|
|
232
|
+
if (settings?.maxFiles && Object.keys(map).length > settings.maxFiles) {
|
|
233
|
+
return NextResponse.json({ errors: [{ message: `${settings.maxFiles} max file uploads exceeded.` }] }, { status: 413 });
|
|
234
|
+
}
|
|
235
|
+
// Normalize operations into a keyed object for path resolution.
|
|
236
|
+
// Single: paths are "variables.file" → use the operation object directly.
|
|
237
|
+
// Batch: paths are "0.variables.file" → use indices as keys in a wrapper object.
|
|
238
|
+
const isBatch = Array.isArray(parsedOperations);
|
|
239
|
+
let operationsRoot;
|
|
240
|
+
if (isBatch) {
|
|
241
|
+
operationsRoot = {};
|
|
242
|
+
for (let i = 0; i < parsedOperations.length; i++) {
|
|
243
|
+
const op = parsedOperations[i];
|
|
244
|
+
if (!op.variables)
|
|
245
|
+
op.variables = {};
|
|
246
|
+
operationsRoot[String(i)] = op;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
const singleOp = parsedOperations;
|
|
251
|
+
if (!singleOp.variables)
|
|
252
|
+
singleOp.variables = {};
|
|
253
|
+
operationsRoot = singleOp;
|
|
144
254
|
}
|
|
255
|
+
// Process files and resolve Upload instances at mapped paths.
|
|
256
|
+
const fileProcessingPromises = [];
|
|
145
257
|
for (const fileKeyInMap of Object.keys(map)) {
|
|
146
258
|
const file = files[fileKeyInMap];
|
|
147
259
|
if (!file) {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
260
|
+
// Per spec: reject Upload promise when file is missing from the request.
|
|
261
|
+
for (const filePath of map[fileKeyInMap]) {
|
|
262
|
+
const missingUpload = new Upload();
|
|
263
|
+
missingUpload.reject(new Error('File missing in the request.'));
|
|
264
|
+
setValueAtPath(operationsRoot, filePath, missingUpload);
|
|
265
|
+
}
|
|
151
266
|
continue;
|
|
152
267
|
}
|
|
153
|
-
if (file.size > settings.maxFileSize) {
|
|
154
|
-
return NextResponse.json({ errors: [{ message: `File ${file.name} size is too large. Maximum allowed size is ${settings.maxFileSize / (1024 * 1024)}MB.` }] }, { status: 413 });
|
|
268
|
+
if (settings?.maxFileSize && file.size > settings.maxFileSize) {
|
|
269
|
+
return NextResponse.json({ errors: [{ message: `File ${file.name} size is too large. Maximum allowed size is ${(settings.maxFileSize / (1024 * 1024)).toFixed(2)}MB.` }] }, { status: 413 });
|
|
155
270
|
}
|
|
156
271
|
const variablePaths = map[fileKeyInMap];
|
|
157
|
-
const filePromise = processUpload(file, settings
|
|
272
|
+
const filePromise = processUpload(file, settings?.allowedTypes)
|
|
158
273
|
.then(uploadInstance => {
|
|
159
|
-
|
|
160
|
-
setValueAtPath(
|
|
161
|
-
}
|
|
274
|
+
for (const filePath of variablePaths) {
|
|
275
|
+
setValueAtPath(operationsRoot, filePath, uploadInstance);
|
|
276
|
+
}
|
|
162
277
|
})
|
|
163
|
-
.catch(error => {
|
|
164
|
-
|
|
278
|
+
.catch((error) => {
|
|
279
|
+
for (const filePath of variablePaths) {
|
|
165
280
|
const uploadError = new Upload();
|
|
166
281
|
uploadError.reject(new Error(`Failed to process file ${file.name}: ${error.message}`));
|
|
167
|
-
setValueAtPath(
|
|
168
|
-
}
|
|
169
|
-
throw new Error(`Failed to process file ${file.name}: ${error.message}`);
|
|
282
|
+
setValueAtPath(operationsRoot, filePath, uploadError);
|
|
283
|
+
}
|
|
170
284
|
});
|
|
171
285
|
fileProcessingPromises.push(filePromise);
|
|
172
286
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
}
|
|
183
|
-
else if (response.body.kind === 'incremental') {
|
|
184
|
-
const { initialResult, subsequentResults } = response.body;
|
|
185
|
-
const collectedSubsequentResults = [];
|
|
186
|
-
for await (const result of subsequentResults) {
|
|
187
|
-
collectedSubsequentResults.push(result);
|
|
287
|
+
await Promise.all(fileProcessingPromises);
|
|
288
|
+
// Execute operations and collect results.
|
|
289
|
+
if (isBatch) {
|
|
290
|
+
const results = [];
|
|
291
|
+
const sortedKeys = Object.keys(operationsRoot).sort((a, b) => Number(a) - Number(b));
|
|
292
|
+
for (const key of sortedKeys) {
|
|
293
|
+
const op = operationsRoot[key];
|
|
294
|
+
const response = await server.executeOperation({ query: op.query, variables: op.variables || {} }, { contextValue: contextValueInput });
|
|
295
|
+
results.push(await collectResponse(response));
|
|
188
296
|
}
|
|
189
|
-
return NextResponse.json(
|
|
190
|
-
initialResult,
|
|
191
|
-
subsequentResults: collectedSubsequentResults,
|
|
192
|
-
});
|
|
297
|
+
return NextResponse.json(results);
|
|
193
298
|
}
|
|
194
|
-
|
|
299
|
+
const response = await server.executeOperation({ query: operationsRoot.query, variables: operationsRoot.variables }, { contextValue: contextValueInput });
|
|
300
|
+
return NextResponse.json(await collectResponse(response));
|
|
195
301
|
}
|
|
196
302
|
catch (error) {
|
|
197
303
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error during upload processing.';
|
package/package.json
CHANGED
|
@@ -7,21 +7,22 @@
|
|
|
7
7
|
"url": "https://github.com/lafittemehdy/graphql-upload-nextjs/issues"
|
|
8
8
|
},
|
|
9
9
|
"dependencies": {
|
|
10
|
-
"@apollo/server": "^4.
|
|
11
|
-
"file-type": "^
|
|
12
|
-
"graphql": "^16.
|
|
10
|
+
"@apollo/server": "^5.4.0",
|
|
11
|
+
"file-type": "^21.3.3",
|
|
12
|
+
"graphql": "^16.13.1",
|
|
13
13
|
"istextorbinary": "^9.5.0",
|
|
14
|
-
"next": "^
|
|
14
|
+
"next": "^16.1.7"
|
|
15
15
|
},
|
|
16
16
|
"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.",
|
|
17
17
|
"devDependencies": {
|
|
18
|
-
"@types/jest": "^
|
|
19
|
-
"@types/node": "^
|
|
20
|
-
"
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
"
|
|
24
|
-
"
|
|
18
|
+
"@types/jest": "^30.0.0",
|
|
19
|
+
"@types/node": "^25.5.0",
|
|
20
|
+
"husky": "^9.1.7",
|
|
21
|
+
"jest": "^30.3.0",
|
|
22
|
+
"nodemon": "^3.1.14",
|
|
23
|
+
"ts-jest": "^29.4.6",
|
|
24
|
+
"typescript": "^5.9.3",
|
|
25
|
+
"undici": "^7.24.4"
|
|
25
26
|
},
|
|
26
27
|
"files": [
|
|
27
28
|
"LICENSE",
|
|
@@ -29,6 +30,9 @@
|
|
|
29
30
|
"index.d.ts",
|
|
30
31
|
"index.js"
|
|
31
32
|
],
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=22.0.0"
|
|
35
|
+
},
|
|
32
36
|
"homepage": "https://github.com/lafittemehdy/graphql-upload-nextjs#readme",
|
|
33
37
|
"keywords": [
|
|
34
38
|
"Apollo Server",
|
|
@@ -45,17 +49,23 @@
|
|
|
45
49
|
"license": "MIT",
|
|
46
50
|
"main": "index.js",
|
|
47
51
|
"name": "graphql-upload-nextjs",
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public",
|
|
54
|
+
"provenance": true
|
|
55
|
+
},
|
|
48
56
|
"repository": {
|
|
49
57
|
"type": "git",
|
|
50
58
|
"url": "git+https://github.com/lafittemehdy/graphql-upload-nextjs.git"
|
|
51
59
|
},
|
|
52
|
-
"type": "module",
|
|
53
|
-
"types": "index.d.ts",
|
|
54
|
-
"version": "0.1.1",
|
|
55
60
|
"scripts": {
|
|
61
|
+
"build": "tsc",
|
|
56
62
|
"dev": "tsc -w | nodemon index.js",
|
|
63
|
+
"prepublishOnly": "npm run build && npm test",
|
|
57
64
|
"start": "tsc && node index.js",
|
|
58
|
-
"
|
|
59
|
-
"
|
|
60
|
-
}
|
|
61
|
-
|
|
65
|
+
"test": "jest",
|
|
66
|
+
"prepare": "husky"
|
|
67
|
+
},
|
|
68
|
+
"type": "module",
|
|
69
|
+
"types": "index.d.ts",
|
|
70
|
+
"version": "2.0.0"
|
|
71
|
+
}
|