Deploy

Description

One of the great things about this library is that it can be deployed to serverless environments. It's super small footprint makes it lightning fast to load, even on cold starts.

The basic use case is simple: we simply need to forward request from some API to our read/write models.

Let's give it a shot using Express:

const {
  readModel,
  writeModel,
} = require('./src')

const express = require('express')
const app = express()

app.use(express.json())

app.get('/:id', (req, res, next) => {
  readModel.getById({ 
    id: req.params.id, 
  })
  .then(obj => {
    if (!obj) throw new Error('Not Found')
    res.json(obj)
  })
  .catch(next)
})

app.post('/', (req, res, next) => {
  writeModel.addTodo(req.body.id, { 
    title: req.body.title,
  })
  .then(res.json.bind(res))
  .catch(next)
})

app.use(function(error, req, res, next) {
  console.log(error)
  res.status(500).json({ message: error.message });
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Or we can use GraphQL, which works really nicely with our setup. Mutations map directly to the write model and Queries to the read model.

We're really not doing very much in either of these examples, we simply forward requests from the API to our read or write model. In the case of GraphQL, it's a bit more explicit.

Serverless Framwork

Now let's look at deploying using the awesome serverless framework.

Following this quickstart, let’s set up our serverless app:

(you’ll also need AWS credentials in your local environment)

Now replace the contents of serverless.yml with this:

Now let's modify the example above to have it work on AWS Lambda

Examples

ExpressGraphQL

The domain in these examples also contain the commands completeTodo and removeTodo.

Last updated

Was this helpful?