feat: solution exercise 2

This commit is contained in:
Kristof Van Miegem 2019-02-07 10:21:28 +01:00
parent c4b07ea259
commit 45f7debb77
3 changed files with 60 additions and 3 deletions

View File

@ -2,17 +2,32 @@ const uuid = require('uuid');
const stores = [ const stores = [
{ {
city: 'Aalst',
id: 'cc406ed9-fc02-4185-b073-8c12b61b5c79', id: 'cc406ed9-fc02-4185-b073-8c12b61b5c79',
name: 'Den Olijfboom', name: 'Den Olijfboom',
number: 38,
postalCode: '9300',
street: 'Molenstraat',
}, },
{ {
city: 'Aalst',
id: '5f2919aa-333a-4745-8166-3002ab30de0e', id: '5f2919aa-333a-4745-8166-3002ab30de0e',
name: 'Pizza Talia' name: 'Pizza Talia',
number: 147,
postalCode: '9300',
street: 'Sint Jobstraat',
} }
]; ];
function createStore({ name }) { function createStore({ city, name, number, postalCode, street }) {
const newStore = { id: uuid(), name }; const newStore = {
city,
id: uuid(),
name,
number,
postalCode,
street,
};
stores.push(newStore); stores.push(newStore);
return newStore; return newStore;
} }

View File

@ -1,9 +1,35 @@
const { UserInputError } = require('apollo-server');
const yup = require('yup');
const data = require('./data'); const data = require('./data');
const createStoreSchema = yup.object()
.shape({
city: yup.string().max(255),
name: yup.string().min(1).max(255).required(),
number: yup
.number()
.required()
.positive()
.integer(),
postalCode: yup.string().max(10),
street: yup.string().max(255),
});
// Resolvers define the technique for fetching the types in the // Resolvers define the technique for fetching the types in the
// schema. // schema.
module.exports = { module.exports = {
Query: { Query: {
stores: () => data.getStores(), stores: () => data.getStores(),
}, },
Mutation: {
createStore: async (parent, { input }) => {
try {
await createStoreSchema.validate(input);
} catch (e) {
throw new UserInputError('Invalid input.', { validationErrors: e.errors });
}
const { city, name, number, postalCode, street } = input;
return data.createStore({ city, name, number, postalCode, street });
}
}
}; };

View File

@ -6,8 +6,12 @@ module.exports = gql`
# Comments in GraphQL are defined with the hash (#) symbol. # Comments in GraphQL are defined with the hash (#) symbol.
# This "Store" type can be used in other type declarations. # This "Store" type can be used in other type declarations.
type Store { type Store {
city: String
id: String id: String
name: String name: String
number: Int
postalCode: String
street: String
} }
# The "Query" type is the root of all GraphQL queries. # The "Query" type is the root of all GraphQL queries.
@ -15,4 +19,16 @@ module.exports = gql`
type Query { type Query {
stores: [Store] stores: [Store]
} }
input StoreInput {
city: String
name: String
number: Int
postalCode: String
street: String
}
type Mutation {
createStore(input: StoreInput): Store
}
`; `;