Improving order-ms with order data 

Let's improve on order-ms a little bit. Here, we will treat some order data and move the types and resolvers from the graphql.ts file to their specific files. To do that, create a file called types.ts with the following content:

import { gql } from 'apollo-server-express'
import { DocumentNode } from 'graphql'

export class OrderGraphQLTypes {
public getTypes(): DocumentNode {
return gql`
type Order {
id: ID!
userId: Int!
quantity: Int!
status: String!
complete: Boolean!
}
type Query {
allOrders: [Order]!
listByOrderId(id: ID): Order!
}
`
}
}

Note that two types are now defined:

  • Order: The order itself
  • Query: Defines the allOrders and listByOrderId functions

Now, create a new file called resolvers.ts with the following content:

import { OrderStatus } from '../models/orderStatus'

const orders = [
{
id: 1,
userId: '1',
quantity: 2,
status: OrderStatus.Placed,
complete: false,
},
{
id: 2,
userId: '2',
quantity: 1,
status: OrderStatus.Placed,
complete: false,
},
{
id: 3,
userId: '3',
quantity: 1,
status: OrderStatus.Approved,
complete: false,
},
{
id: 4,
userId: '1',
quantity: 10,
status: OrderStatus.Delivered,
complete: true,
},
]

export class OrderGraphQLResolvers {
public getResolvers(): IResolvers {
return {
Query: {
allOrders: () => orders,
listByOrderId: (root, args, context) => {
return orders.find(order => order.id === Number(args.id))
},
},
}
}
}

We created a fake array of orders for this example and a class called OrderGraphQLResolvers, which is going to handle the allOrders and listByOrderId functions for us.

Now, go back to the graphql.ts file and change the way we are setting the types and resolvers so that we can use those new classes:

import { ApolloServer, IResolvers } from 'apollo-server-express'
import { DocumentNode } from 'graphql'
import { OrderGraphQLResolvers } from './resolvers'
import { OrderGraphQLTypes } from './types'

export class GraphQL {
public typeDefs: DocumentNode
public resolvers: IResolvers
public server: ApolloServer

constructor() {
this.typeDefs = new OrderGraphQLTypes().getTypes()
this.resolvers = new OrderGraphQLResolvers().getResolvers()

this.server = new ApolloServer({
typeDefs: this.typeDefs,
resolvers: this.resolvers,
})
}

public setup(app): void {
this.server.applyMiddleware({ app: app })
}
}

Start the application and test it out to get allOrders:

Getting allOrders

We also need to get the order by ID:

Getting the order by ID
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.13.201