# Getting started

This tutorial takes you through the steps to create a mock server from scratch.

# Find a location

Your mock server should live in a directory of your project or a package within your monorepo:

  • In the case of a simple repo (ie. not a monorepo), we'll create a /mock-server directory at the root of the repo.
  • In the case of a monorepo, we'll create a mock-server package.
  • In case you're working with multiple repos, a separate repo/package can be created.

# Using yarn create

The fastest way to get started is to use yarn create, this will create a new package with everything setup:

  • TypeScript
  • Watch mode (using esbuild-runner)
  • Linting (following DC standards)
yarn create @datacamp/poser-server

This will ask you the name of the server (used to create the directory) and will generate all files.


# Manual setup

This section shows how to setup a poser server manually. The code examples are assuming you're creating an ES module (ie. type: "module" in package.json). If you prefer CommonJS, simply use require() instead of imports. It's also possible to use with TypeScript.

# Install Poser

Install the package @datacamp/poser:

yarn add @datacamp/poser
npm install @datacamp/poser

# Import Poser

In your directory of choice, create an index.js file:

index.js
import { poser } from '@datacamp/poser';

poser.start();

We can now start our "empty" mock server:

node index.js

This should produce the following output:

Kong user_id = 123
Registering mock services

> Poser ready on http://localhost:1000

# Add a mock service

Add a simple mock service with a very small GraphQL API:

index.js
import { poser } from '@datacamp/poser';

poser.registerService('my-service', {
  graphql: {
    typeDefs: `
      type Query {
        books: [Book]
      }
      type Book {
        id: Int
        title: String
      }
    `,
  },
});

poser.start();

When starting the server, you should see the mock service my-service registered:

Kong user_id = 123
Registering mock services
  my-service
    - GraphQL mounted on /my-service/graphql
    - Store inspector mounted on /my-service/store

> Poser ready on http://localhost:1000

Now visit http://localhost:1000 to see your service in the UI. This UI will give you access to logs and a GraphQL client.

All queries and type fields will be auto-mocked, read more on how to customize the GraphQL responses.

# Add nodemon

A mock server is made to be manipulated during development, to fit the values of specific uses-cases. To help with this, you can use nodemon to keep the running server in sync with code changes:

First, install nodemon:

yarn add nodemon -D
npm install nodemon --save-dev

Then create a start script in package.json to run Poser with nodemon:

package.json
{
  "scripts": {
    "start": "nodemon --ext js,json,graphql index.js"
  }
}

Now start your server using yarn start. All changes, including .graphql files, will restart the server.