GraphQL API with database
This serverless Codehooks example backend exposes a graphql endpoint for CRUD operations.
- You can use Postman to test the API. Postman automatically fetches the GraphQL schema and gives you auto-completion ๐ค
- Data is persisted in the NoSQL document database.
Visit the official GraphQL site to learn more about GraphQL.
- Create a project with the
coho create
CLI command. - Change to the project directory and install using
npm i codehooks-js graphql graphql-tools
. - Open the index.js file in your favorite code editor and enter the following code.
Main file (index.js)โ
The index.js file defines the schema, the resolvers and the single GraphQL route we need.
import { app, Datastore } from 'codehooks-js';
import { graphql } from 'graphql';
import { makeExecutableSchema } from 'graphql-tools';
// Construct a schema, using GraphQL schema language
const typeDefs = `
type Member {
id: ID
name: String!
age: Int
active: Boolean
}
type Query {
ping: String
member(id: ID!): Member!
allMembers: [Member]
}
type Mutation {
addMember(name: String! age:Int active:Boolean): Member!
updateMember(id: ID! name: String age:Int active:Boolean): Member!
deleteMember(id: ID!): ID
}
`;
// implement resolvers for queries and mutations
const resolvers = {
Query: {
ping: () => {
return 'Pong!';
},
member: async (obj, { id }, { db } ) => {
const { _id, ...rest } = await db.getOne('members', id);
return { id: _id, ...rest };
},
allMembers: async (obj, args, { db }) => {
const members = await db.getArray('members');
return members.map(({_id, ...member }) => ({id: _id, ...member })); // map _id to id
}
},
Mutation: {
addMember: async (obj, input, { db }) => {
const {_id, ...rest } = await db.insertOne('members', input);
return { id: _id, ...rest };
},
updateMember: async(obj, {id, ...data }, { db }) => {
return db.updateOne('members', id, data);
},
deleteMember: async(obj, {id}, { db }) => {
const result = await db.removeOne('members', id);
return result._id;
},
}
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
// Create the default graphql POST route
app.post('/graphql', async (req, res) => {
const conn = await Datastore.open();
const response = await graphql({
schema,
source: req.body.query,
contextValue: { db: conn }
});
res.json(response);
});
export default app.init(); // Bind functions to the serverless cloud
Deploymentโ
You can deploy the code with this CLI command:
coho deploy
Test the deployed GraphQL endpointโ
Test your deployed code with Postman using GraphQL support (recommended).
Postman reads the schema from the codehooks.io /graphql
endpoint and gives you code completion.
Use the CLI command coho info
to see the HTTP endpoint and the API tokens for the project space.
You can also use cURL to use the GraphQL API to add and read dataโ
Add one member mutationโ
curl --location --request POST 'https://graphqltest-4pmq.api.codehooks.io/dev/graphql' \
--header 'x-apikey: 66e33428-45d3-4811-be21-58fa6d5d5e91' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"mutation { addMember(name: \"Mr Codehook\", age: 33) { id name }}"}'
Get all members queryโ
curl --location --request POST 'https://graphqltest-4pmq.api.codehooks.io/dev/graphql' \
--header 'x-apikey: 66e33428-45d3-4811-be21-58fa6d5d5e91' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"{allMembers {id name }}"}'
Use a local serverless server instead of deployingโ
If you don't want to create an account yet, you can also test your codehooks.io GraphQL backend locally using this command:
coho localserver
Conclusionโ
We've demonstrated how you can set up a simple serverless GraphQL server using very little JavaScript code. We hope this has inspired you to check out what is possible to do with codehooks.io's compact backend and database.
To learn more about creating backends with Node.js and codehooks.io, check out the documentation or the blog