graphql-upload-nextjs 0.1.1 → 1.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.
Files changed (5) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +364 -333
  3. package/index.d.ts +3 -3
  4. package/index.js +3 -3
  5. package/package.json +62 -61
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Mehdy Ben Hafaiedh
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Mehdy Ben Hafaiedh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,333 +1,364 @@
1
- # graphql-upload-nextjs
2
-
3
- [![Integration Test](https://github.com/lafittemehdy/graphql-upload-nextjs/actions/workflows/integration-test.yml/badge.svg)](https://github.com/lafittemehdy/graphql-upload-nextjs/actions/workflows/integration-test.yml)
4
-
5
- `graphql-upload-nextjs` is a robust package that enables seamless file uploads in a Next.js environment using GraphQL. This package is designed to integrate easily with Apollo Server, allowing you to handle file uploads in your GraphQL mutations with ease and efficiency.
6
-
7
- ## Features
8
-
9
- - Supports file uploads via GraphQL in a Next.js environment.
10
- - Utilizes Apollo Server for handling GraphQL operations.
11
- - Provides utilities for processing and validating file uploads.
12
- - Handles various file types with customizable MIME type and size restrictions.
13
- - Offers a clear and structured approach for integrating file uploads into your GraphQL schema.
14
-
15
- ## Installation
16
-
17
- To install the package, use one of the following commands:
18
-
19
- ```bash
20
- npm install graphql-upload-nextjs
21
- # or
22
- yarn add graphql-upload-nextjs
23
- # or
24
- pnpm add graphql-upload-nextjs
25
- ```
26
-
27
- ## Usage
28
-
29
- ### Importing the Package
30
-
31
- Import the necessary components from the package:
32
-
33
- ```javascript
34
- import { GraphQLUpload, type File, uploadProcess } from 'graphql-upload-nextjs'
35
-
36
- import { ApolloServer } from '@apollo/server'
37
- import { NextRequest } from 'next/server'
38
- import { createWriteStream } from 'fs'
39
- import { pipeline } from 'stream'
40
- import { startServerAndCreateNextHandler } from '@as-integrations/next'
41
-
42
- // Optional: Use the gql module from Apollo Client for syntax highlighting.
43
- // This package is already installed for the client side.
44
- import { gql } from '@apollo/client'
45
- ```
46
-
47
- ### Defining the GraphQL Schema and Resolvers
48
-
49
- Define your GraphQL schema and resolvers:
50
-
51
- ```javascript
52
- // For this example, we define the GraphQL schema and resolvers below.
53
- const typeDefs = gql`
54
- # Custom scalar type for handling file uploads.
55
- scalar Upload
56
- type File {
57
- encoding: String!
58
- fileName: String!
59
- fileSize: Int!
60
- mimeType: String!
61
- uri: String!
62
- }
63
- type Query {
64
- default: Boolean!
65
- }
66
- type Mutation {
67
- uploadFile(file: Upload!): File!
68
- uploadFiles(files: [Upload!]!): [File!]!
69
- }
70
- `
71
-
72
- const resolvers = {
73
- Mutation: {
74
- // This is a simplified example for demonstration purposes only; do not use this code in a production environment.
75
- uploadFile: async (_parent: void, { file }: { file: Promise<File> }, { ip }: Context) => {
76
- try {
77
- const { createReadStream, encoding, fileName, fileSize, mimeType } = await file
78
-
79
- // Use a Promise to handle the asynchronous file saving operation.
80
- return new Promise((resolve, reject) => {
81
- pipeline(
82
- createReadStream(),
83
- // This example stores the file in the 'public' directory for simplicity, you should NEVER do this.
84
- createWriteStream(`./public/${fileName}`),
85
- (error) => {
86
- if (error) {
87
- console.error('File upload pipeline error:', error)
88
- reject(new Error('Error during file upload.'))
89
- } else {
90
- console.log(`${ip} successfully uploaded ${fileName}`)
91
- // Resolve the promise with the file details for the GraphQL response.
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
- }
102
- },
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
- },
135
- // Add the custom scalar type for file uploads.
136
- Upload: GraphQLUpload
137
- }
138
- ```
139
-
140
- ### Creating the Apollo Server
141
-
142
- Create the Apollo Server instance and set up the request handler:
143
-
144
- ```javascript
145
- // Where data and requests meet (and hopefully get along).
146
- const server = new ApolloServer({ resolvers, typeDefs })
147
-
148
- interface Context {
149
- ip: string // IP address of the client.
150
- req: NextRequest // The Next.js request object.
151
- }
152
-
153
- // You'll usually want to authenticate users here, but for this example, we'll just get the IP address.
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
- }
162
-
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
- const requestHandler = async (request: NextRequest) => {
169
- try {
170
- // Handle file uploads specifically if the request is multipart/form-data.
171
- if (request.headers.get('content-type')?.includes('multipart/form-data')) {
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.')
194
- }
195
- }
196
-
197
- // Export request handlers for GET, POST, and OPTIONS methods.
198
- export const GET = requestHandler
199
- export const POST = requestHandler
200
- export const OPTIONS = requestHandler
201
- ```
202
-
203
- ### Executing the Mutations
204
-
205
- When sending requests to your GraphQL server, you'll need to structure your mutation and variables correctly. This package adheres to the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec) for file uploads.
206
-
207
- **Single File Upload (`uploadFile` mutation):**
208
-
209
- *GraphQL Operation:*
210
- ```graphql
211
- mutation UploadFile($file: Upload!) {
212
- uploadFile(file: $file) {
213
- fileName
214
- mimeType
215
- encoding
216
- uri
217
- fileSize
218
- }
219
- }
220
- ```
221
-
222
- *GraphQL Variables:*
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.
227
-
228
- The `{"file": null}` structure illustrates how the `operations` part of the multipart request is formed, where `null` acts as a placeholder for the actual file content that is sent in a separate part of the request. You generally don't need to construct this manually when using a client library.
229
-
230
- *Example with a client library (conceptual):*
231
- ```javascript
232
- // In your frontend code
233
- import { gql, useMutation } from '@apollo/client'; // Or your client of choice
234
-
235
- const UPLOAD_FILE_MUTATION = gql`
236
- mutation UploadFile($file: Upload!) {
237
- uploadFile(file: $file) { fileName }
238
- }
239
- `;
240
-
241
- function MyUploader() {
242
- const [uploadFileMutation] = useMutation(UPLOAD_FILE_MUTATION);
243
-
244
- const handleChange = (event) => {
245
- const file = event.target.files[0];
246
- if (file) {
247
- uploadFileMutation({ variables: { file } });
248
- }
249
- };
250
-
251
- return <input type="file" onChange={handleChange} />;
252
- }
253
- ```
254
-
255
- **Multiple File Upload (`uploadFiles` mutation):**
256
-
257
- *GraphQL Operation:*
258
- ```graphql
259
- mutation UploadFiles($files: [Upload!]!) {
260
- uploadFiles(files: $files) {
261
- fileName
262
- mimeType
263
- encoding
264
- uri
265
- fileSize
266
- }
267
- }
268
- ```
269
-
270
- *GraphQL Variables:*
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.
275
-
276
- The `{"files": [null, null]}` structure illustrates the `operations` part, with `null` placeholders for file content sent separately.
277
-
278
- *Example with a client library (conceptual):*
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
- `;
286
-
287
- function MyMultiUploader() {
288
- const [uploadFilesMutation] = useMutation(UPLOAD_FILES_MUTATION);
289
-
290
- const handleChange = (event) => {
291
- const files = Array.from(event.target.files);
292
- if (files.length > 0) {
293
- uploadFilesMutation({ variables: { files } });
294
- }
295
- };
296
-
297
- return <input type="file" multiple onChange={handleChange} />;
298
- }
299
- ```
300
-
301
- ## Example
302
-
303
- An example project demonstrating how to integrate GraphQL file uploads into a typical Next.js starter application is available in the repository under `graphql-upload-nextjs/examples/example-graphql-upload-nextjs/`. This example uses a relative path to the main package for live code testing and development.
304
-
305
- ## Development Notes
306
-
307
- For development, the example uses a relative path to import the package. This setup allows you to test the code live:
308
-
309
- ```javascript
310
- import { GraphQLUpload, type File, uploadProcess } from '../../../../../../index'
311
- ```
312
-
313
- To use the example as a standalone, update the import to:
314
-
315
- ```javascript
316
- import { GraphQLUpload, type File, uploadProcess } from 'graphql-upload-nextjs'
317
- ```
318
-
319
- ## Contributing
320
-
321
- Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request.
322
-
323
- ## License
324
-
325
- This project is licensed under the MIT License. See the [LICENSE](https://github.com/lafittemehdy/graphql-upload-nextjs/blob/master/LICENSE) file for more information.
326
-
327
- ## Acknowledgements
328
-
329
- I would like to express my sincere gratitude to [meabed](https://github.com/meabed) for their excellent work on [graphql-upload-ts](https://github.com/meabed/graphql-upload-ts), which served as a valuable reference and inspiration for this project. I am also grateful to [jaydenseric](https://github.com/jaydenseric) for developing the original specifications for [graphql-upload](https://github.com/jaydenseric/graphql-upload).
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.
332
-
333
- Finally, I would like to extend my heartfelt gratitude to my mom for her unwavering support, including hosting me and allowing me to dedicate my time to working on open-source software.
1
+ # graphql-upload-nextjs
2
+
3
+ `graphql-upload-nextjs` is a robust package that enables seamless file uploads in a Next.js environment using GraphQL. This package is designed to integrate easily with Apollo Server, allowing you to handle file uploads in your GraphQL mutations with ease and efficiency.
4
+
5
+ ## Features
6
+
7
+ - Supports file uploads via GraphQL in a Next.js environment.
8
+ - Utilizes Apollo Server for handling GraphQL operations.
9
+ - Provides utilities for processing and validating file uploads.
10
+ - Handles various file types with customizable MIME type and size restrictions.
11
+ - Offers a clear and structured approach for integrating file uploads into your GraphQL schema.
12
+
13
+ ## Installation
14
+
15
+ To install the package, use one of the following commands:
16
+
17
+ ```bash
18
+ npm install graphql-upload-nextjs
19
+ # or
20
+ yarn add graphql-upload-nextjs
21
+ # or
22
+ pnpm add graphql-upload-nextjs
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ### Importing the Package
28
+
29
+ Import the necessary components from the package:
30
+
31
+ ```javascript
32
+ import { GraphQLUpload, type File, uploadProcess } from 'graphql-upload-nextjs'
33
+
34
+ import { ApolloServer } from '@apollo/server'
35
+ import { NextRequest } from 'next/server'
36
+ import { createWriteStream } from 'fs'
37
+ import { pipeline } from 'stream'
38
+ import { startServerAndCreateNextHandler } from '@as-integrations/next'
39
+
40
+ // Optional: Use the gql module from Apollo Client for syntax highlighting.
41
+ // This package is already installed for the client side.
42
+ import { gql } from '@apollo/client'
43
+ ```
44
+
45
+ ### Defining the GraphQL Schema and Resolvers
46
+
47
+ Define your GraphQL schema and resolvers:
48
+
49
+ ```javascript
50
+ // For this example, we define the GraphQL schema and resolvers below.
51
+ const typeDefs = gql`
52
+ # Custom scalar type for handling file uploads.
53
+ scalar Upload
54
+ type File {
55
+ encoding: String!
56
+ fileName: String!
57
+ fileSize: Int!
58
+ mimeType: String!
59
+ uri: String!
60
+ }
61
+ type Query {
62
+ default: Boolean!
63
+ }
64
+ type Mutation {
65
+ uploadFile(file: Upload!): File!
66
+ uploadFiles(files: [Upload!]!): [File!]!
67
+ }
68
+ `
69
+
70
+ const resolvers = {
71
+ Mutation: {
72
+ uploadFile: async (
73
+ _parent: undefined,
74
+ { file }: { file: Promise<File> },
75
+ _context: Context,
76
+ ): Promise<GraphQLFileResponse> => {
77
+ try {
78
+ const { createReadStream, encoding, fileName, fileSize, mimeType } =
79
+ await file;
80
+ const allowedTypes = ["image/jpeg", "image/png", "text/plain"];
81
+ const maxFileSize = 10 * 1024 * 1024; // 10MB
82
+
83
+ if (!allowedTypes.includes(mimeType)) {
84
+ throw new Error(`File type ${mimeType} is not allowed.`);
85
+ }
86
+
87
+ if (fileSize > maxFileSize) {
88
+ throw new Error(`File size exceeds the limit of 10MB.`);
89
+ }
90
+
91
+ return new Promise<GraphQLFileResponse>((resolve, reject) => {
92
+ pipeline(
93
+ createReadStream(),
94
+ // IMPORTANT: Storing files in 'public' is insecure for production. Use secure storage.
95
+ createWriteStream(`./public/${fileName}`),
96
+ (error) => {
97
+ if (error) {
98
+ reject(new Error("Error during file upload."));
99
+ } else {
100
+ resolve({
101
+ encoding,
102
+ fileName,
103
+ fileSize,
104
+ mimeType,
105
+ uri: `http://localhost:3000/${fileName}`,
106
+ });
107
+ }
108
+ },
109
+ );
110
+ });
111
+ } catch (_error) {
112
+ throw new Error("Failed to handle file upload.");
113
+ }
114
+ },
115
+ uploadFiles: async (
116
+ _parent: undefined,
117
+ { files }: { files: Promise<File>[] },
118
+ _context: Context,
119
+ ): Promise<GraphQLFileResponse[]> => {
120
+ const resolvedFileObjects = await Promise.all(files);
121
+ const allowedTypes = ["image/jpeg", "image/png", "text/plain"];
122
+ const maxFileSize = 10 * 1024 * 1024; // 10MB
123
+
124
+ const processingPromises = resolvedFileObjects.map(async (fileObject) => {
125
+ if (
126
+ !fileObject ||
127
+ typeof fileObject.createReadStream !== "function" ||
128
+ !fileObject.fileName
129
+ ) {
130
+ throw new Error(
131
+ `Invalid file data encountered for one of the files.`,
132
+ );
133
+ }
134
+
135
+ const { createReadStream, encoding, fileName, fileSize, mimeType } =
136
+ fileObject;
137
+
138
+ if (!allowedTypes.includes(mimeType)) {
139
+ throw new Error(
140
+ `File type ${mimeType} is not allowed for ${fileName}.`,
141
+ );
142
+ }
143
+
144
+ if (fileSize > maxFileSize) {
145
+ throw new Error(`File ${fileName} size exceeds the limit of 10MB.`);
146
+ }
147
+
148
+ return new Promise<GraphQLFileResponse>((resolve, reject) => {
149
+ const readStream = createReadStream();
150
+ if (typeof readStream.pipe !== "function") {
151
+ return reject(
152
+ new Error(`Failed to get a readable stream for ${fileName}.`),
153
+ );
154
+ }
155
+ pipeline(
156
+ readStream,
157
+ // IMPORTANT: Insecure storage. Use secure solution in production.
158
+ createWriteStream(`./public/${fileName}`),
159
+ (error) => {
160
+ if (error) {
161
+ reject(new Error(`Error during upload of ${fileName}.`));
162
+ } else {
163
+ resolve({
164
+ encoding,
165
+ fileName,
166
+ fileSize,
167
+ mimeType,
168
+ uri: `http://localhost:3000/${fileName}`,
169
+ });
170
+ }
171
+ },
172
+ );
173
+ });
174
+ });
175
+
176
+ return Promise.all(processingPromises);
177
+ },
178
+ },
179
+ Query: {
180
+ default: async () => true
181
+ },
182
+ // Add the custom scalar type for file uploads.
183
+ Upload: GraphQLUpload
184
+ }
185
+ ```
186
+
187
+ ### Creating the Apollo Server
188
+
189
+ Create the Apollo Server instance and set up the request handler:
190
+
191
+ ```javascript
192
+ const server = new ApolloServer({ resolvers, typeDefs });
193
+
194
+ interface Context {
195
+ ip: string;
196
+ req: NextRequest;
197
+ [key: string]: unknown;
198
+ }
199
+
200
+ const contextHandler = async (
201
+ req: NextRequest,
202
+ authenticated: string | boolean = false,
203
+ ): Promise<Context> => {
204
+ const ip = req.headers.get("x-forwarded-for") || "";
205
+ if (authenticated) return { ip, req };
206
+ return { ip, req };
207
+ };
208
+
209
+ interface ServerExecuteOperationParams {
210
+ query: string;
211
+ variables: Record<string, unknown>;
212
+ }
213
+
214
+ interface ExpectedServerType<TContext extends Record<string, unknown>> {
215
+ executeOperation: (
216
+ params: ServerExecuteOperationParams,
217
+ context: { contextValue: TContext },
218
+ ) => Promise<GraphQLResponse<TContext>>;
219
+ }
220
+
221
+ const handler = startServerAndCreateNextHandler<NextRequest, Context>(server, {
222
+ context: contextHandler,
223
+ });
224
+
225
+ const requestHandler = async (request: NextRequest) => {
226
+ try {
227
+ if (request.headers.get("content-type")?.includes("multipart/form-data")) {
228
+ // IMPORTANT: Authenticate before processing uploads. Placeholder 'User' used.
229
+ const context = await contextHandler(request, "User");
230
+ return await uploadProcess(
231
+ request,
232
+ context,
233
+ server as ExpectedServerType<Context>,
234
+ );
235
+ }
236
+ return handler(request);
237
+ } catch (_error) {
238
+ throw new Error("Failed to process request.");
239
+ }
240
+ };
241
+
242
+ // Export request handlers for GET, POST, and OPTIONS methods.
243
+ export const GET = requestHandler;
244
+ export const POST = requestHandler;
245
+ export const OPTIONS = requestHandler;
246
+ ```
247
+
248
+ ### Executing the Mutations
249
+
250
+ When sending requests to your GraphQL server, you'll need to structure your mutation and variables correctly. This package adheres to the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec) for file uploads.
251
+
252
+ **Single File Upload (`uploadFile` mutation):**
253
+
254
+ *GraphQL Operation:*
255
+ ```graphql
256
+ mutation UploadFile($file: Upload!) {
257
+ uploadFile(file: $file) {
258
+ fileName
259
+ mimeType
260
+ encoding
261
+ uri
262
+ fileSize
263
+ }
264
+ }
265
+ ```
266
+
267
+ *GraphQL Variables:*
268
+ The key in the variables object (`"file"`) must match the argument name in your GraphQL mutation (`$file`).
269
+ When using a GraphQL client library (e.g., Apollo Client, urql, Relay):
270
+ * You'll typically pass the browser's `File` object (e.g., from an `<input type="file">`) directly as the value for the `file` variable.
271
+ * The client library automatically constructs the multipart/form-data request according to the GraphQL multipart request specification.
272
+
273
+ The `{"file": null}` structure illustrates how the `operations` part of the multipart request is formed, where `null` acts as a placeholder for the actual file content that is sent in a separate part of the request. You generally don't need to construct this manually when using a client library.
274
+
275
+ *Example with a client library (conceptual):*
276
+ ```javascript
277
+ // In your frontend code
278
+ import { gql, useMutation } from '@apollo/client'; // Or your client of choice
279
+
280
+ const UPLOAD_FILE_MUTATION = gql`
281
+ mutation UploadFile($file: Upload!) {
282
+ uploadFile(file: $file) { fileName }
283
+ }
284
+ `;
285
+
286
+ function MyUploader() {
287
+ const [uploadFileMutation] = useMutation(UPLOAD_FILE_MUTATION);
288
+
289
+ const handleChange = (event) => {
290
+ const file = event.target.files[0];
291
+ if (file) {
292
+ uploadFileMutation({ variables: { file } });
293
+ }
294
+ };
295
+
296
+ return <input type="file" onChange={handleChange} />;
297
+ }
298
+ ```
299
+
300
+ **Multiple File Upload (`uploadFiles` mutation):**
301
+
302
+ *GraphQL Operation:*
303
+ ```graphql
304
+ mutation UploadFiles($files: [Upload!]!) {
305
+ uploadFiles(files: $files) {
306
+ fileName
307
+ mimeType
308
+ encoding
309
+ uri
310
+ fileSize
311
+ }
312
+ }
313
+ ```
314
+
315
+ *GraphQL Variables:*
316
+ Similarly, the key `"files"` must match the argument name (`$files`).
317
+ When using a GraphQL client library:
318
+ * You'll pass an array of `File` objects as the value for the `files` variable.
319
+ * The client library handles the multipart request construction.
320
+
321
+ The `{"files": [null, null]}` structure illustrates the `operations` part, with `null` placeholders for file content sent separately.
322
+
323
+ *Example with a client library (conceptual):*
324
+ ```javascript
325
+ // In your frontend code
326
+ const UPLOAD_FILES_MUTATION = gql`
327
+ mutation UploadFiles($files: [Upload!]!) {
328
+ uploadFiles(files: $files) { fileName }
329
+ }
330
+ `;
331
+
332
+ function MyMultiUploader() {
333
+ const [uploadFilesMutation] = useMutation(UPLOAD_FILES_MUTATION);
334
+
335
+ const handleChange = (event) => {
336
+ const files = Array.from(event.target.files);
337
+ if (files.length > 0) {
338
+ uploadFilesMutation({ variables: { files } });
339
+ }
340
+ };
341
+
342
+ return <input type="file" multiple onChange={handleChange} />;
343
+ }
344
+ ```
345
+
346
+ ## Example
347
+
348
+ An example project demonstrating how to integrate GraphQL file uploads into a typical Next.js starter application is available in the repository under `graphql-upload-nextjs/examples/example-graphql-upload-nextjs/`.
349
+
350
+ ## Contributing
351
+
352
+ Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request.
353
+
354
+ ## License
355
+
356
+ This project is licensed under the MIT License. See the [LICENSE](https://github.com/lafittemehdy/graphql-upload-nextjs/blob/master/LICENSE) file for more information.
357
+
358
+ ## Acknowledgements
359
+
360
+ I would like to express my sincere gratitude to [meabed](https://github.com/meabed) for their excellent work on [graphql-upload-ts](https://github.com/meabed/graphql-upload-ts), which served as a valuable reference and inspiration for this project. I am also grateful to [jaydenseric](https://github.com/jaydenseric) for developing the original specifications for [graphql-upload](https://github.com/jaydenseric/graphql-upload).
361
+
362
+ 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.
363
+
364
+ Finally, I would like to extend my 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
@@ -49,8 +49,8 @@ export declare function uploadProcess<TContext extends Record<string, unknown>>(
49
49
  executeOperation: (params: ServerExecuteOperationParams, context: {
50
50
  contextValue: TContext;
51
51
  }) => Promise<GraphQLResponse<TContext>>;
52
- }, settings: {
53
- allowedTypes: string[];
54
- maxFileSize: number;
52
+ }, settings?: {
53
+ allowedTypes?: string[];
54
+ maxFileSize?: number;
55
55
  }): Promise<NextResponse<any>>;
56
56
  export {};
package/index.js CHANGED
@@ -111,7 +111,7 @@ async function processUpload(file, allowedTypes) {
111
111
  // isText check failed, proceed with original mimeType
112
112
  }
113
113
  }
114
- if (!allowedTypes.includes(mimeType)) {
114
+ if (allowedTypes && !allowedTypes.includes(mimeType)) {
115
115
  throw new Error(`File type ${mimeType} is not allowed. Allowed types: ${allowedTypes.join(', ')}`);
116
116
  }
117
117
  const upload = new Upload();
@@ -150,11 +150,11 @@ export async function uploadProcess(request, contextValueInput, server, settings
150
150
  });
151
151
  continue;
152
152
  }
153
- if (file.size > settings.maxFileSize) {
153
+ if (settings?.maxFileSize && file.size > settings.maxFileSize) {
154
154
  return NextResponse.json({ errors: [{ message: `File ${file.name} size is too large. Maximum allowed size is ${settings.maxFileSize / (1024 * 1024)}MB.` }] }, { status: 413 });
155
155
  }
156
156
  const variablePaths = map[fileKeyInMap];
157
- const filePromise = processUpload(file, settings.allowedTypes)
157
+ const filePromise = processUpload(file, settings?.allowedTypes)
158
158
  .then(uploadInstance => {
159
159
  variablePaths.forEach(path => {
160
160
  setValueAtPath(operations, path, uploadInstance);
package/package.json CHANGED
@@ -1,61 +1,62 @@
1
- {
2
- "author": {
3
- "email": "lafittemehdy@gmail.com",
4
- "name": "Lafitte Mehdy"
5
- },
6
- "bugs": {
7
- "url": "https://github.com/lafittemehdy/graphql-upload-nextjs/issues"
8
- },
9
- "dependencies": {
10
- "@apollo/server": "^4.12.0",
11
- "file-type": "^19.0.0",
12
- "graphql": "^16.8.2",
13
- "istextorbinary": "^9.5.0",
14
- "next": "^15.3.2"
15
- },
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
- "devDependencies": {
18
- "@types/jest": "^29.5.14",
19
- "@types/node": "^20.14.5",
20
- "jest": "^29.7.0",
21
- "nodemon": "^3.1.3",
22
- "ts-jest": "^29.3.2",
23
- "typescript": "^5.4.5",
24
- "undici": "^6.19.2"
25
- },
26
- "files": [
27
- "LICENSE",
28
- "README.md",
29
- "index.d.ts",
30
- "index.js"
31
- ],
32
- "homepage": "https://github.com/lafittemehdy/graphql-upload-nextjs#readme",
33
- "keywords": [
34
- "Apollo Server",
35
- "File streaming",
36
- "File upload",
37
- "GraphQL file upload",
38
- "GraphQL resolver",
39
- "GraphQL upload",
40
- "GraphQL",
41
- "Next.js integration",
42
- "Next.js",
43
- "Server-side upload"
44
- ],
45
- "license": "MIT",
46
- "main": "index.js",
47
- "name": "graphql-upload-nextjs",
48
- "repository": {
49
- "type": "git",
50
- "url": "git+https://github.com/lafittemehdy/graphql-upload-nextjs.git"
51
- },
52
- "type": "module",
53
- "types": "index.d.ts",
54
- "version": "0.1.1",
55
- "scripts": {
56
- "dev": "tsc -w | nodemon index.js",
57
- "start": "tsc && node index.js",
58
- "build": "tsc",
59
- "test": "NODE_OPTIONS=--experimental-vm-modules jest"
60
- }
61
- }
1
+ {
2
+ "author": {
3
+ "email": "lafittemehdy@gmail.com",
4
+ "name": "Lafitte Mehdy"
5
+ },
6
+ "bugs": {
7
+ "url": "https://github.com/lafittemehdy/graphql-upload-nextjs/issues"
8
+ },
9
+ "dependencies": {
10
+ "@apollo/server": "^5.0.0",
11
+ "file-type": "^21.0.0",
12
+ "graphql": "^16.11.0",
13
+ "istextorbinary": "^9.5.0",
14
+ "next": "^15.5.3"
15
+ },
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
+ "devDependencies": {
18
+ "@types/jest": "^30.0.0",
19
+ "@types/node": "^24.5.2",
20
+ "cross-env": "^7.0.3",
21
+ "jest": "^30.1.3",
22
+ "nodemon": "^3.1.10",
23
+ "ts-jest": "^29.4.4",
24
+ "typescript": "^5.9.2",
25
+ "undici": "^7.16.0"
26
+ },
27
+ "files": [
28
+ "LICENSE",
29
+ "README.md",
30
+ "index.d.ts",
31
+ "index.js"
32
+ ],
33
+ "homepage": "https://github.com/lafittemehdy/graphql-upload-nextjs#readme",
34
+ "keywords": [
35
+ "Apollo Server",
36
+ "File streaming",
37
+ "File upload",
38
+ "GraphQL file upload",
39
+ "GraphQL resolver",
40
+ "GraphQL upload",
41
+ "GraphQL",
42
+ "Next.js integration",
43
+ "Next.js",
44
+ "Server-side upload"
45
+ ],
46
+ "license": "MIT",
47
+ "main": "index.js",
48
+ "name": "graphql-upload-nextjs",
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/lafittemehdy/graphql-upload-nextjs.git"
52
+ },
53
+ "scripts": {
54
+ "dev": "tsc -w | nodemon index.js",
55
+ "start": "tsc && node index.js",
56
+ "build": "tsc",
57
+ "test": "echo \"Error: no test specified\" && exit 1"
58
+ },
59
+ "type": "module",
60
+ "types": "index.d.ts",
61
+ "version": "1.0.0"
62
+ }