I needed a quick and fast Restful API mock that will run in a container. Normally we use Wire Mocks which is a .Net libruary but Node is much faster right? Ohh shots fired! 🤣
Create And Test App
- Use NPM to scaffold some template files
1 | mkdir mymock |
- Create
index.js
, you may have called this something related to your mocked service and pop in your mocked routes.5007
be any avalible port, check what ports are already mocked in your repository.
1 | import express from "express"; |
You can also access environment variables should they exist
1 | const myVar = process.env.THIS_IS_MY_VAR |
- Edit
package.json
and add
1 | "type": "module", |
- Run the script with
npm start
from your console. You can then test it from your browser at http://localhost:5007/foos/1
You should get
1 | {"params_fooid":"1","params_barid":"2"} |
You can then refactor the app to mock any routes and results, for the above we are mocking /foos/:fooId
so /foos/1
which responds with some json and express
will ensure status 200 OK (its like magic)
Stop the app with
CRTL C
which will free up port 5007.You will probably push this to git, its common if part of a mono-repo to now have a
.gitignore
formymock
as it is an application.
1 | # Dependency directories |
Docker
Do you even code if you dont package up your things into a nice container :D
- Create the
.dockerignore
file and add
1 | node_modules |
.dockerignore
is a configuration file that describes file(s) & directory(s) that you want to exclude when building a Docker image.
- Create the Dockerfile.
node:slim
is a lightweight node image andnpm ci
will clean install the project. The healthcheck fails then exit with code 1. Any code other than 0 means there was some sadness.
1 | FROM node:slim |
- Create an image and test it the same as above at http://localhost:5007/foos/1.
Some notes
-t
tags the new image-it
means create an interactive bash shell in the container and connect to it-rm
removes the container when it exits.
1 | docker build -t mymockimage:1 . ~ . means build in the current dir context |
Stop the app with
CRTL C
which will free up port 5007.Cleanup the image
1 | docker image rm mymockimage:1 |