graphql-upload-nextjs 0.1.1

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 -0
  2. package/README.md +333 -0
  3. package/index.d.ts +56 -0
  4. package/index.js +200 -0
  5. package/package.json +61 -0
package/LICENSE ADDED
@@ -0,0 +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.
package/README.md ADDED
@@ -0,0 +1,333 @@
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.
package/index.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import { GraphQLScalarType, GraphQLError } from 'graphql';
2
+ import { NextResponse } from 'next/server.js';
3
+ import type { GraphQLResponse } from '@apollo/server';
4
+ export interface File {
5
+ createReadStream: () => NodeJS.ReadableStream;
6
+ encoding: string;
7
+ fileName: string;
8
+ fileSize: number;
9
+ mimeType: string;
10
+ }
11
+ export interface FileStream extends FormDataFile {
12
+ stream: () => Promise<NodeJS.ReadableStream>;
13
+ }
14
+ export interface FormDataFile {
15
+ lastModified: number;
16
+ name: string;
17
+ size: number;
18
+ type: string;
19
+ }
20
+ /**
21
+ * Represents an instance of a file upload.
22
+ * Holds a promise that resolves with the file details once processed.
23
+ */
24
+ export declare class Upload {
25
+ file?: File;
26
+ promise: Promise<File>;
27
+ reject: (reason?: Error | string) => void;
28
+ resolve: (file: File) => void;
29
+ constructor();
30
+ }
31
+ export declare const GraphQLUpload: GraphQLScalarType<Promise<File> | GraphQLError, never>;
32
+ export declare function streamToBuffer(stream: NodeJS.ReadableStream): Promise<Buffer>;
33
+ export declare function bufferToStream(buffer: Buffer): NodeJS.ReadableStream;
34
+ export declare function sanitizeAndValidateJSON(input: string): unknown;
35
+ interface ServerExecuteOperationParams {
36
+ query: string;
37
+ variables: Record<string, unknown>;
38
+ }
39
+ export interface MinimalRequest {
40
+ formData: () => Promise<FormData>;
41
+ headers: {
42
+ get: (name: string) => string | null;
43
+ };
44
+ }
45
+ /**
46
+ * Processes a GraphQL multipart request with file uploads.
47
+ */
48
+ export declare function uploadProcess<TContext extends Record<string, unknown>>(request: MinimalRequest, contextValueInput: TContext, server: {
49
+ executeOperation: (params: ServerExecuteOperationParams, context: {
50
+ contextValue: TContext;
51
+ }) => Promise<GraphQLResponse<TContext>>;
52
+ }, settings: {
53
+ allowedTypes: string[];
54
+ maxFileSize: number;
55
+ }): Promise<NextResponse<any>>;
56
+ export {};
package/index.js ADDED
@@ -0,0 +1,200 @@
1
+ import { GraphQLScalarType, GraphQLError } from 'graphql';
2
+ import { NextResponse } from 'next/server.js';
3
+ import { fileTypeFromBuffer } from 'file-type';
4
+ import { isText } from 'istextorbinary';
5
+ /**
6
+ * Represents an instance of a file upload.
7
+ * Holds a promise that resolves with the file details once processed.
8
+ */
9
+ export class Upload {
10
+ file;
11
+ promise;
12
+ reject = () => { };
13
+ resolve = () => { };
14
+ constructor() {
15
+ this.promise = new Promise((resolve, reject) => {
16
+ this.resolve = (file) => {
17
+ this.file = file;
18
+ resolve(file);
19
+ };
20
+ this.reject = reject;
21
+ });
22
+ this.promise.catch(() => { });
23
+ }
24
+ }
25
+ export const GraphQLUpload = new GraphQLScalarType({
26
+ description: 'The Upload scalar type represents a file upload.',
27
+ name: 'Upload',
28
+ parseLiteral(node) { throw new GraphQLError('Upload literal unsupported.', { nodes: node }); },
29
+ parseValue(value) { return value instanceof Upload ? value.promise : new GraphQLError('Upload value invalid.'); },
30
+ serialize() { throw new GraphQLError('Upload serialization unsupported.'); }
31
+ });
32
+ async function extractFiles(formData) {
33
+ const files = {};
34
+ for (const [key, value] of Array.from(formData.entries())) {
35
+ if (value instanceof globalThis.File) {
36
+ files[key] = value;
37
+ }
38
+ }
39
+ return files;
40
+ }
41
+ export async function streamToBuffer(stream) {
42
+ const chunks = [];
43
+ for await (const chunk of stream) {
44
+ if (Buffer.isBuffer(chunk)) {
45
+ chunks.push(chunk);
46
+ }
47
+ else if (typeof chunk === 'string') {
48
+ chunks.push(Buffer.from(chunk));
49
+ }
50
+ else {
51
+ chunks.push(Buffer.from(chunk));
52
+ }
53
+ }
54
+ return Buffer.concat(chunks);
55
+ }
56
+ export function bufferToStream(buffer) {
57
+ const { Readable } = require('stream');
58
+ const stream = new Readable();
59
+ stream.push(buffer);
60
+ stream.push(null);
61
+ return stream;
62
+ }
63
+ export function sanitizeAndValidateJSON(input) {
64
+ try {
65
+ const result = JSON.parse(input);
66
+ if (typeof result !== 'object' || result === null) {
67
+ throw new Error('Invalid JSON structure: not an object.');
68
+ }
69
+ return result;
70
+ }
71
+ catch (error) {
72
+ throw new Error(`Invalid JSON input: ${error.message}`);
73
+ }
74
+ }
75
+ function setValueAtPath(obj, path, value) {
76
+ const keys = path.split('.');
77
+ let current = obj;
78
+ for (let i = 0; i < keys.length - 1; i++) {
79
+ const key = keys[i];
80
+ const nextKeyIsArrayIndex = /^\d+$/.test(keys[i + 1]);
81
+ if (!current[key] || typeof current[key] !== (nextKeyIsArrayIndex ? 'object' : 'object')) {
82
+ if (current[key] && ((nextKeyIsArrayIndex && !Array.isArray(current[key])) || (!nextKeyIsArrayIndex && Array.isArray(current[key])))) {
83
+ // Path conflict, overwriting.
84
+ }
85
+ current[key] = nextKeyIsArrayIndex ? [] : {};
86
+ }
87
+ current = current[key];
88
+ }
89
+ current[keys[keys.length - 1]] = value;
90
+ }
91
+ async function processUpload(file, allowedTypes) {
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;
102
+ }
103
+ else {
104
+ try {
105
+ const isTextResult = await isText(file.name, buffer);
106
+ if (isTextResult === true) {
107
+ mimeType = 'text/plain';
108
+ }
109
+ }
110
+ catch (err) {
111
+ // isText check failed, proceed with original mimeType
112
+ }
113
+ }
114
+ if (!allowedTypes.includes(mimeType)) {
115
+ throw new Error(`File type ${mimeType} is not allowed. Allowed types: ${allowedTypes.join(', ')}`);
116
+ }
117
+ const upload = new Upload();
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;
126
+ }
127
+ /**
128
+ * Processes a GraphQL multipart request with file uploads.
129
+ */
130
+ export async function uploadProcess(request, contextValueInput, server, settings) {
131
+ try {
132
+ const formData = await request.formData();
133
+ const files = await extractFiles(formData);
134
+ const mapString = formData.get('map');
135
+ const operationsString = formData.get('operations');
136
+ if (!mapString || !operationsString) {
137
+ throw new Error('Missing map or operations in form data.');
138
+ }
139
+ const map = sanitizeAndValidateJSON(mapString);
140
+ const operations = sanitizeAndValidateJSON(operationsString);
141
+ const fileProcessingPromises = [];
142
+ if (!operations.variables) {
143
+ operations.variables = {};
144
+ }
145
+ for (const fileKeyInMap of Object.keys(map)) {
146
+ const file = files[fileKeyInMap];
147
+ if (!file) {
148
+ map[fileKeyInMap].forEach(path => {
149
+ setValueAtPath(operations, path, null);
150
+ });
151
+ continue;
152
+ }
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 });
155
+ }
156
+ const variablePaths = map[fileKeyInMap];
157
+ const filePromise = processUpload(file, settings.allowedTypes)
158
+ .then(uploadInstance => {
159
+ variablePaths.forEach(path => {
160
+ setValueAtPath(operations, path, uploadInstance);
161
+ });
162
+ })
163
+ .catch(error => {
164
+ variablePaths.forEach(path => {
165
+ const uploadError = new Upload();
166
+ uploadError.reject(new Error(`Failed to process file ${file.name}: ${error.message}`));
167
+ setValueAtPath(operations, path, uploadError);
168
+ });
169
+ throw new Error(`Failed to process file ${file.name}: ${error.message}`);
170
+ });
171
+ fileProcessingPromises.push(filePromise);
172
+ }
173
+ try {
174
+ await Promise.all(fileProcessingPromises);
175
+ }
176
+ catch (processingError) {
177
+ // Individual file processing errors are handled by rejecting Upload.promise.
178
+ }
179
+ const response = await server.executeOperation({ query: operations.query, variables: operations.variables }, { contextValue: contextValueInput });
180
+ if (response.body.kind === 'single') {
181
+ return NextResponse.json(response.body.singleResult);
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);
188
+ }
189
+ return NextResponse.json({
190
+ initialResult,
191
+ subsequentResults: collectedSubsequentResults,
192
+ });
193
+ }
194
+ return NextResponse.json({ errors: [{ message: 'Unexpected server response format' }] }, { status: 500 });
195
+ }
196
+ catch (error) {
197
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error during upload processing.';
198
+ return NextResponse.json({ errors: [{ message: `Error processing upload: ${errorMessage}` }] }, { status: 500 });
199
+ }
200
+ }
package/package.json ADDED
@@ -0,0 +1,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": "^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
+ }