Simple serverless GraphQL using codehooks.io
Tags: webdev, serverless, graphql, node
Published: 2023-01-05 11:53:24

Codehooks.io is an easy to use serverless backend tool for Node.js. In this very short blog post, we'll show you how to create a really simple GraphQL-powered persistent backend using a little JavaScript and codehooks.io's built-in NoSQL database.
 
* You can use [Postman](https://postman.com) 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](https://www.graphql.com/) to learn more about GraphQL.

The following steps assume you have a codehooks.io account and the [CLI](https://www.npmjs.com/package/codehooks) installed. You can install it with: `npm install codehooks -g`. Codehooks.io is free to use up to a limit of 5000 API calls and 5000 data objects. 

Here we go:

1. Create a project with the `coho create` CLI command. 
2. Change to the project directory and install using  `npm i codehooks-js graphql graphql-tools`.
3. 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. 

```js
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

Codehooks.io JavaScript code is easy to deploy. Just change directory to your development folder and deploy the code with this [CLI command](https://codehooks.io/docs/cli#deploy):

```bash
coho deploy
```

## Test the deployed GraphQL endpoint

We recommend that you test your deployed code with [Postman using GraphQL support](https://www.postman.com/graphql) (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**

```bash
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**

```bash
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 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:

```bash
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](https://codehooks.io/docs) or the [blog](https://codehooks.io/blog)