feat: Switch GraphQL server from Yoga v2 to Apollo v4 (#8959)
This commit is contained in:
@@ -1,5 +1,9 @@
|
||||
import corsMiddleware from 'cors';
|
||||
import { createServer, renderGraphiQL } from '@graphql-yoga/node';
|
||||
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js';
|
||||
import { ApolloServer } from '@apollo/server';
|
||||
import { expressMiddleware } from '@apollo/server/express4';
|
||||
import { ApolloServerPluginCacheControlDisabled } from '@apollo/server/plugin/disabled';
|
||||
import express from 'express';
|
||||
import { execute, subscribe } from 'graphql';
|
||||
import { SubscriptionServer } from 'subscriptions-transport-ws';
|
||||
import { handleParseErrors, handleParseHeaders, handleParseSession } from '../middlewares';
|
||||
@@ -33,16 +37,13 @@ class ParseGraphQLServer {
|
||||
try {
|
||||
return {
|
||||
schema: await this.parseGraphQLSchema.load(),
|
||||
context: ({ req: { info, config, auth } }) => ({
|
||||
info,
|
||||
config,
|
||||
auth,
|
||||
}),
|
||||
maskedErrors: false,
|
||||
multipart: {
|
||||
fileSize: this._transformMaxUploadSizeToBytes(
|
||||
this.parseServer.config.maxUploadSize || '20mb'
|
||||
),
|
||||
context: async ({ req, res }) => {
|
||||
res.set('access-control-allow-origin', req.get('origin') || '*');
|
||||
return {
|
||||
info: req.info,
|
||||
config: req.config,
|
||||
auth: req.auth,
|
||||
};
|
||||
},
|
||||
};
|
||||
} catch (e) {
|
||||
@@ -57,8 +58,21 @@ class ParseGraphQLServer {
|
||||
if (schemaRef === newSchemaRef && this._server) {
|
||||
return this._server;
|
||||
}
|
||||
const options = await this._getGraphQLOptions();
|
||||
this._server = createServer(options);
|
||||
const { schema, context } = await this._getGraphQLOptions();
|
||||
const apollo = new ApolloServer({
|
||||
csrfPrevention: {
|
||||
// See https://www.apollographql.com/docs/router/configuration/csrf/
|
||||
// needed since we use graphql upload
|
||||
requestHeaders: ['X-Parse-Application-Id'],
|
||||
},
|
||||
introspection: true,
|
||||
plugins: [ApolloServerPluginCacheControlDisabled()],
|
||||
schema,
|
||||
});
|
||||
await apollo.start();
|
||||
this._server = expressMiddleware(apollo, {
|
||||
context,
|
||||
});
|
||||
return this._server;
|
||||
}
|
||||
|
||||
@@ -79,14 +93,21 @@ class ParseGraphQLServer {
|
||||
if (!app || !app.use) {
|
||||
requiredParameter('You must provide an Express.js app instance!');
|
||||
}
|
||||
|
||||
app.use(this.config.graphQLPath, corsMiddleware());
|
||||
app.use(this.config.graphQLPath, handleParseHeaders);
|
||||
app.use(this.config.graphQLPath, handleParseSession);
|
||||
app.use(this.config.graphQLPath, handleParseErrors);
|
||||
app.use(this.config.graphQLPath, async (req, res) => {
|
||||
app.use(
|
||||
this.config.graphQLPath,
|
||||
graphqlUploadExpress({
|
||||
maxFileSize: this._transformMaxUploadSizeToBytes(
|
||||
this.parseServer.config.maxUploadSize || '20mb'
|
||||
),
|
||||
})
|
||||
);
|
||||
app.use(this.config.graphQLPath, express.json(), async (req, res, next) => {
|
||||
const server = await this._getServer();
|
||||
return server(req, res);
|
||||
return server(req, res, next);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -94,20 +115,33 @@ class ParseGraphQLServer {
|
||||
if (!app || !app.get) {
|
||||
requiredParameter('You must provide an Express.js app instance!');
|
||||
}
|
||||
|
||||
app.get(
|
||||
this.config.playgroundPath ||
|
||||
requiredParameter('You must provide a config.playgroundPath to applyPlayground!'),
|
||||
(_req, res) => {
|
||||
res.setHeader('Content-Type', 'text/html');
|
||||
res.write(
|
||||
renderGraphiQL({
|
||||
endpoint: this.config.graphQLPath,
|
||||
subscriptionEndpoint: this.config.subscriptionsPath,
|
||||
headers: JSON.stringify({
|
||||
'X-Parse-Application-Id': this.parseServer.config.appId,
|
||||
'X-Parse-Master-Key': this.parseServer.config.masterKey,
|
||||
}),
|
||||
})
|
||||
`<div id="sandbox" style="position:absolute;top:0;right:0;bottom:0;left:0"></div>
|
||||
<script src="https://embeddable-sandbox.cdn.apollographql.com/_latest/embeddable-sandbox.umd.production.min.js"></script>
|
||||
<script>
|
||||
new window.EmbeddedSandbox({
|
||||
target: "#sandbox",
|
||||
endpointIsEditable: false,
|
||||
initialEndpoint: "${JSON.stringify(this.config.graphQLPath)}",
|
||||
handleRequest: (endpointUrl, options) => {
|
||||
return fetch(endpointUrl, {
|
||||
...options,
|
||||
headers: {
|
||||
...options.headers,
|
||||
'X-Parse-Application-Id': "${JSON.stringify(this.parseServer.config.appId)}",
|
||||
'X-Parse-Master-Key': "${JSON.stringify(this.parseServer.config.masterKey)}",
|
||||
},
|
||||
})
|
||||
},
|
||||
});
|
||||
// advanced options: https://www.apollographql.com/docs/studio/explorer/sandbox#embedding-sandbox
|
||||
</script>`
|
||||
);
|
||||
res.end();
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
GraphQLUnionType,
|
||||
} from 'graphql';
|
||||
import { toGlobalId } from 'graphql-relay';
|
||||
import GraphQLUpload from 'graphql-upload/GraphQLUpload.js';
|
||||
|
||||
class TypeValidationError extends Error {
|
||||
constructor(value, type) {
|
||||
@@ -222,11 +223,6 @@ const DATE = new GraphQLScalarType({
|
||||
},
|
||||
});
|
||||
|
||||
const GraphQLUpload = new GraphQLScalarType({
|
||||
name: 'Upload',
|
||||
description: 'The Upload scalar type represents a file upload.',
|
||||
});
|
||||
|
||||
const BYTES = new GraphQLScalarType({
|
||||
name: 'Bytes',
|
||||
description:
|
||||
|
||||
@@ -1,33 +1,61 @@
|
||||
import { GraphQLNonNull } from 'graphql';
|
||||
import { request } from 'http';
|
||||
import { getExtension } from 'mime';
|
||||
import { mutationWithClientMutationId } from 'graphql-relay';
|
||||
import Parse from 'parse/node';
|
||||
import * as defaultGraphQLTypes from './defaultGraphQLTypes';
|
||||
import logger from '../../logger';
|
||||
|
||||
// Handle GraphQL file upload and proxy file upload to GraphQL server url specified in config;
|
||||
// `createFile` is not directly called by Parse Server to leverage standard file upload mechanism
|
||||
const handleUpload = async (upload, config) => {
|
||||
const data = Buffer.from(await upload.arrayBuffer());
|
||||
const fileName = upload.name;
|
||||
const type = upload.type;
|
||||
|
||||
if (!data || !data.length) {
|
||||
throw new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'Invalid file upload.');
|
||||
}
|
||||
|
||||
if (fileName.length > 128) {
|
||||
throw new Parse.Error(Parse.Error.INVALID_FILE_NAME, 'Filename too long.');
|
||||
}
|
||||
|
||||
if (!fileName.match(/^[_a-zA-Z0-9][a-zA-Z0-9@\.\ ~_-]*$/)) {
|
||||
throw new Parse.Error(Parse.Error.INVALID_FILE_NAME, 'Filename contains invalid characters.');
|
||||
}
|
||||
|
||||
const { createReadStream, filename, mimetype } = await upload;
|
||||
const headers = { ...config.headers };
|
||||
delete headers['accept-encoding'];
|
||||
delete headers['accept'];
|
||||
delete headers['connection'];
|
||||
delete headers['host'];
|
||||
delete headers['content-length'];
|
||||
const stream = createReadStream();
|
||||
try {
|
||||
const ext = getExtension(mimetype);
|
||||
const fullFileName = filename.endsWith(`.${ext}`) ? filename : `${filename}.${ext}`;
|
||||
const serverUrl = new URL(config.serverURL);
|
||||
const fileInfo = await new Promise((resolve, reject) => {
|
||||
const req = request(
|
||||
{
|
||||
hostname: serverUrl.hostname,
|
||||
port: serverUrl.port,
|
||||
path: `${serverUrl.pathname}/files/${fullFileName}`,
|
||||
method: 'POST',
|
||||
headers,
|
||||
},
|
||||
res => {
|
||||
let data = '';
|
||||
res.on('data', chunk => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on('end', () => {
|
||||
try {
|
||||
resolve(JSON.parse(data));
|
||||
} catch (e) {
|
||||
reject(new Parse.Error(Parse.error, data));
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
stream.pipe(req);
|
||||
stream.on('end', () => {
|
||||
req.end();
|
||||
});
|
||||
});
|
||||
return {
|
||||
fileInfo: await config.filesController.createFile(config, fileName, data, type),
|
||||
fileInfo,
|
||||
};
|
||||
} catch (e) {
|
||||
stream.destroy();
|
||||
logger.error('Error creating a file: ', e);
|
||||
throw new Parse.Error(Parse.Error.FILE_SAVE_ERROR, `Could not store file: ${fileName}.`);
|
||||
throw new Parse.Error(Parse.Error.FILE_SAVE_ERROR, `Could not store file: ${filename}.`);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Parse from 'parse/node';
|
||||
import { GraphQLYogaError } from '@graphql-yoga/node';
|
||||
import { GraphQLError } from 'graphql';
|
||||
|
||||
export function enforceMasterKeyAccess(auth) {
|
||||
if (!auth.isMaster) {
|
||||
@@ -16,7 +16,7 @@ export function toGraphQLError(error) {
|
||||
code = Parse.Error.INTERNAL_SERVER_ERROR;
|
||||
message = 'Internal server error';
|
||||
}
|
||||
return new GraphQLYogaError(message, { code });
|
||||
return new GraphQLError(message, { extensions: { code } });
|
||||
}
|
||||
|
||||
export const extractKeysAndInclude = selectedFields => {
|
||||
|
||||
Reference in New Issue
Block a user