Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GraphQL: Nested File Upload #6372

Merged
merged 5 commits into from
Jan 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 141 additions & 15 deletions spec/ParseGraphQLServer.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const req = require('../lib/request');
const fetch = require('node-fetch');
const FormData = require('form-data');
const ws = require('ws');
require('./helper');
const pluralize = require('pluralize');
const { getMainDefinition } = require('apollo-utilities');
const { ApolloLink, split } = require('apollo-link');
Expand Down Expand Up @@ -907,7 +908,7 @@ describe('ParseGraphQLServer', () => {
.map(field => field.name)
.sort();

expect(inputFields).toEqual(['clientMutationId', 'userFields']);
expect(inputFields).toEqual(['clientMutationId', 'fields']);
});

it('should have clientMutationId in sign up mutation payload', async () => {
Expand Down Expand Up @@ -7114,7 +7115,7 @@ describe('ParseGraphQLServer', () => {
variables: {
input: {
clientMutationId,
userFields: {
fields: {
username: 'user1',
password: 'user1',
someField: 'someValue',
Expand All @@ -7129,6 +7130,63 @@ describe('ParseGraphQLServer', () => {
expect(typeof result.data.signUp.viewer.sessionToken).toBe('string');
});

it('should login with user', async () => {
const clientMutationId = uuidv4();
const userSchema = new Parse.Schema('_User');
parseServer = await global.reconfigureServer({
publicServerURL: 'http://localhost:13377/parse',
auth: {
myAuth: {
module: global.mockCustomAuthenticator('parse', 'graphql'),
},
},
});

userSchema.addString('someField');
await userSchema.update();
await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear();
const result = await apolloClient.mutate({
mutation: gql`
mutation LogInWith($input: LogInWithInput!) {
logInWith(input: $input) {
clientMutationId
viewer {
sessionToken
user {
someField
}
}
}
}
`,
variables: {
input: {
clientMutationId,
authData: {
myAuth: {
id: 'parse',
password: 'graphql',
},
},
fields: {
someField: 'someValue',
},
},
},
});

expect(result.data.logInWith.clientMutationId).toEqual(
clientMutationId
);
expect(result.data.logInWith.viewer.sessionToken).toBeDefined();
expect(result.data.logInWith.viewer.user.someField).toEqual(
'someValue'
);
expect(typeof result.data.logInWith.viewer.sessionToken).toBe(
'string'
);
});

it('should log the user in', async () => {
const clientMutationId = uuidv4();
const user = new Parse.User();
Expand Down Expand Up @@ -9170,6 +9228,7 @@ describe('ParseGraphQLServer', () => {
);

const someFieldValue = result.data.createFile.fileInfo.name;
const someFieldObjectValue = result.data.createFile.fileInfo;

await apolloClient.mutate({
mutation: gql`
Expand All @@ -9195,38 +9254,105 @@ describe('ParseGraphQLServer', () => {

await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear();

const createResult = await apolloClient.mutate({
mutation: gql`
const body2 = new FormData();
body2.append(
'operations',
JSON.stringify({
query: `
mutation CreateSomeObject(
$fields1: CreateSomeClassFieldsInput
$fields2: CreateSomeClassFieldsInput
$fields3: CreateSomeClassFieldsInput
) {
createSomeClass1: createSomeClass(
input: { fields: $fields1 }
) {
someClass {
id
someField {
name
url
}
}
}
createSomeClass2: createSomeClass(
input: { fields: $fields2 }
) {
someClass {
id
someField {
name
url
}
}
}
createSomeClass3: createSomeClass(
input: { fields: $fields3 }
) {
someClass {
id
someField {
name
url
}
}
}
}
`,
variables: {
fields1: {
someField: someFieldValue,
},
fields2: {
someField: someFieldValue.name,
`,
variables: {
fields1: {
someField: { file: someFieldValue },
},
fields2: {
someField: {
file: {
name: someFieldObjectValue.name,
url: someFieldObjectValue.url,
__type: 'File',
},
},
},
fields3: {
someField: { upload: null },
},
},
},
})
);
body2.append(
'map',
JSON.stringify({ 1: ['variables.fields3.someField.upload'] })
);
body2.append('1', 'My File Content', {
filename: 'myFileName.txt',
contentType: 'text/plain',
});

res = await fetch('http://localhost:13377/graphql', {
method: 'POST',
headers,
body: body2,
});
expect(res.status).toEqual(200);
const result2 = JSON.parse(await res.text());
expect(
result2.data.createSomeClass1.someClass.someField.name
).toEqual(jasmine.stringMatching(/_myFileName.txt$/));
expect(
result2.data.createSomeClass1.someClass.someField.url
).toEqual(jasmine.stringMatching(/_myFileName.txt$/));
expect(
result2.data.createSomeClass2.someClass.someField.name
).toEqual(jasmine.stringMatching(/_myFileName.txt$/));
expect(
result2.data.createSomeClass2.someClass.someField.url
).toEqual(jasmine.stringMatching(/_myFileName.txt$/));
expect(
result2.data.createSomeClass3.someClass.someField.name
).toEqual(jasmine.stringMatching(/_myFileName.txt$/));
expect(
result2.data.createSomeClass3.someClass.someField.url
).toEqual(jasmine.stringMatching(/_myFileName.txt$/));

const schema = await new Parse.Schema('SomeClass').get();
expect(schema.fields.someField.type).toEqual('File');

Expand Down Expand Up @@ -9266,7 +9392,7 @@ describe('ParseGraphQLServer', () => {
}
`,
variables: {
id: createResult.data.createSomeClass1.someClass.id,
id: result2.data.createSomeClass1.someClass.id,
},
});

Expand All @@ -9277,8 +9403,8 @@ describe('ParseGraphQLServer', () => {
expect(getResult.data.someClass.someField.url).toEqual(
result.data.createFile.fileInfo.url
);
expect(getResult.data.findSomeClass1.edges.length).toEqual(1);
expect(getResult.data.findSomeClass2.edges.length).toEqual(1);
expect(getResult.data.findSomeClass1.edges.length).toEqual(3);
expect(getResult.data.findSomeClass2.edges.length).toEqual(3);

res = await fetch(getResult.data.someClass.someField.url);

Expand Down
16 changes: 16 additions & 0 deletions src/GraphQL/loaders/defaultGraphQLTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,20 @@ const FILE_INFO = new GraphQLObjectType({
},
});

const FILE_INPUT = new GraphQLInputObjectType({
name: 'FileInput',
fields: {
file: {
description: 'A File Scalar can be an url or a FileInfo object.',
type: FILE,
},
upload: {
description: 'Use this field if you want to create a new file.',
type: GraphQLUpload,
},
},
});

const GEO_POINT_FIELDS = {
latitude: {
description: 'This is the latitude.',
Expand Down Expand Up @@ -1244,6 +1258,7 @@ const load = parseGraphQLSchema => {
parseGraphQLSchema.addGraphQLType(BYTES, true);
parseGraphQLSchema.addGraphQLType(FILE, true);
parseGraphQLSchema.addGraphQLType(FILE_INFO, true);
parseGraphQLSchema.addGraphQLType(FILE_INPUT, true);
parseGraphQLSchema.addGraphQLType(GEO_POINT_INPUT, true);
parseGraphQLSchema.addGraphQLType(GEO_POINT, true);
parseGraphQLSchema.addGraphQLType(PARSE_OBJECT, true);
Expand Down Expand Up @@ -1301,6 +1316,7 @@ export {
SELECT_INPUT,
FILE,
FILE_INFO,
FILE_INPUT,
GEO_POINT_FIELDS,
GEO_POINT_INPUT,
GEO_POINT,
Expand Down
101 changes: 49 additions & 52 deletions src/GraphQL/loaders/filesMutations.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,53 @@ import Parse from 'parse/node';
import * as defaultGraphQLTypes from './defaultGraphQLTypes';
import logger from '../../logger';

const handleUpload = async (upload, config) => {
const { createReadStream, filename, mimetype } = await upload;
let data = null;
if (createReadStream) {
const stream = createReadStream();
data = await new Promise((resolve, reject) => {
const chunks = [];
stream
.on('error', reject)
.on('data', chunk => chunks.push(chunk))
.on('end', () => resolve(Buffer.concat(chunks)));
});
}

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.'
);
}

try {
return {
fileInfo: await config.filesController.createFile(
config,
filename,
data,
mimetype
),
};
} catch (e) {
logger.error('Error creating a file: ', e);
throw new Parse.Error(
Parse.Error.FILE_SAVE_ERROR,
`Could not store file: ${filename}.`
);
}
};

const load = parseGraphQLSchema => {
const createMutation = mutationWithClientMutationId({
name: 'CreateFile',
Expand All @@ -26,57 +73,7 @@ const load = parseGraphQLSchema => {
try {
const { upload } = args;
const { config } = context;

const { createReadStream, filename, mimetype } = await upload;
let data = null;
if (createReadStream) {
const stream = createReadStream();
data = await new Promise((resolve, reject) => {
const chunks = [];
stream
.on('error', reject)
.on('data', chunk => chunks.push(chunk))
.on('end', () => resolve(Buffer.concat(chunks)));
});
}

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.'
);
}

try {
return {
fileInfo: await config.filesController.createFile(
config,
filename,
data,
mimetype
),
};
} catch (e) {
logger.error('Error creating a file: ', e);
throw new Parse.Error(
Parse.Error.FILE_SAVE_ERROR,
`Could not store file: ${filename}.`
);
}
return handleUpload(upload, config);
} catch (e) {
parseGraphQLSchema.handleError(e);
}
Expand All @@ -97,4 +94,4 @@ const load = parseGraphQLSchema => {
);
};

export { load };
export { load, handleUpload };
Loading