| 8 | // Handle GraphQL file upload and proxy file upload to GraphQL server url specified in config; |
| 9 | // `createFile` is not directly called by Parse Server to leverage standard file upload mechanism |
| 10 | const handleUpload = async (upload, config) => { |
| 11 | const { createReadStream, filename, mimetype } = await upload; |
| 12 | const headers = { ...config.headers }; |
| 13 | delete headers['accept-encoding']; |
| 14 | delete headers['accept']; |
| 15 | delete headers['connection']; |
| 16 | delete headers['host']; |
| 17 | delete headers['content-length']; |
| 18 | const stream = createReadStream(); |
| 19 | const mime = (await import('mime')).default; |
| 20 | try { |
| 21 | const ext = mime.getExtension(mimetype); |
| 22 | const fullFileName = filename.endsWith(`.${ext}`) ? filename : `${filename}.${ext}`; |
| 23 | const serverUrl = new URL(config.serverURL); |
| 24 | const fileInfo = await new Promise((resolve, reject) => { |
| 25 | const req = request( |
| 26 | { |
| 27 | hostname: serverUrl.hostname, |
| 28 | port: serverUrl.port, |
| 29 | path: `${serverUrl.pathname}/files/${fullFileName}`, |
| 30 | method: 'POST', |
| 31 | headers, |
| 32 | }, |
| 33 | res => { |
| 34 | let data = ''; |
| 35 | res.on('data', chunk => { |
| 36 | data += chunk; |
| 37 | }); |
| 38 | res.on('end', () => { |
| 39 | try { |
| 40 | resolve(JSON.parse(data)); |
| 41 | } catch { |
| 42 | reject(new Parse.Error(Parse.error, data)); |
| 43 | } |
| 44 | }); |
| 45 | } |
| 46 | ); |
| 47 | stream.pipe(req); |
| 48 | stream.on('end', () => { |
| 49 | req.end(); |
| 50 | }); |
| 51 | }); |
| 52 | return { |
| 53 | fileInfo, |
| 54 | }; |
| 55 | } catch (e) { |
| 56 | stream.destroy(); |
| 57 | logger.error('Error creating a file: ', e); |
| 58 | throw new Parse.Error(Parse.Error.FILE_SAVE_ERROR, `Could not store file: ${filename}.`); |
| 59 | } |
| 60 | }; |
| 61 | |
| 62 | const load = parseGraphQLSchema => { |
| 63 | const createMutation = mutationWithClientMutationId({ |