Skip to content

Commit 20f9a1e

Browse files
committed
Genesis commit
0 parents  commit 20f9a1e

File tree

13 files changed

+2160
-0
lines changed

13 files changed

+2160
-0
lines changed

.env.example

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
SERVER_NAME=mock-json-server
2+
SERVER_PORT=3000
3+
SERVER_PREFIX=v1

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
/.idea
2+
/.vscode
3+
.env
4+
app/data/*
5+
!app/data/.gitkeep

Dockerfile

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
FROM node:16.16.0-alpine
2+
3+
USER root
4+
WORKDIR /usr/local
5+
COPY *.json ./
6+
COPY *.js ./
7+
8+
RUN npm install
9+
ENV PATH /usr/local/node_modules/.bin:$PATH
10+
11+
WORKDIR /usr/local/app
12+
COPY app ./
13+
14+
EXPOSE 3000
15+
USER node
16+
17+
#ENTRYPOINT ["tail", "-f", "/dev/null"]
18+
CMD ["npm", "start"]

README.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Mock API Server
2+
Based on [json-server](https://github.com/typicode/json-server)
3+
4+
## Getting Started
5+
There is a couple of environment variables that can be set if you want to over-ride the defaults
6+
7+
| Name | Description | Default |
8+
|---------------|---------------------------------|------------------|
9+
| SERVER_NAME | Prefix for the docker conatiner | mock-json-server |
10+
| SERVER_PORT | Exposed port for the sever | 3000 |
11+
| SERVER_PREFIX | Prefix for the urls | v1 |
12+
13+
If you want to change these, copy the _.env.example_ file to _.env_ and set the values
14+
```shell
15+
cp .env.example .env
16+
```
17+
18+
Once your environment is set, bring up the container like you would any docker-compose poroject;
19+
```shell
20+
docker-compose build
21+
docker-compose up -d
22+
```
23+
and
24+
```shell
25+
docker-compose down
26+
```
27+
when you are done.
28+
29+
## Managing Your Data
30+
Your data is stored in _json_ files located in the `app/data` folder.
31+
Example:
32+
```json
33+
[
34+
{ "id": 1, "name": "wibble", "age": "20" },
35+
{ "id": 2, "name": "wabble", "age": "30" },
36+
{ "id": 3, "name": "wubble", "age": "40" }
37+
]
38+
```
39+
This setup works by automatically reading all the json files in the data folder.
40+
You can add/edit them without bringing down the container.
41+
42+
N.B. These files are more of a seed in concept.
43+
If you use a `POST` route, the new data will not show up in the file.
44+
45+
To see the whole database at any time just hit up the database endpoint.
46+
```shell
47+
GET /db
48+
```
49+
50+
For more information see the json-server [docs](https://github.com/typicode/json-server#getting-started)
51+
## Managing your routes
52+
As per the standard [json-server](https://github.com/typicode/json-server#routes), routes are automatically created based on the names of the data files.
53+
So a data file called `posts.json`, will have the endpoints;
54+
```shell
55+
GET /posts
56+
GET /posts/1
57+
POST /posts
58+
PUT /posts/1
59+
PATCH /posts/1
60+
DELETE /posts/1
61+
```
62+
63+
They are also available using the environment prefix variable.
64+
```shell
65+
GET /v1/posts
66+
GET /v1/posts/1
67+
POST /v1/posts
68+
PUT /v1/posts/1
69+
PATCH /v1/posts/1
70+
DELETE /v1/posts/1
71+
```
72+
73+
You can add your own custom routes in the `data/routes.js` file.
74+
See the main [json-server](https://github.com/typicode/json-server#add-custom-routes) documentation for more details.
75+
76+
# Have fun

app/data/.gitkeep

Whitespace-only changes.

app/routes.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module.exports = {
2+
"/:resource/:id/show": "/:resource/:id"
3+
}

data.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const {readdirSync, readFileSync} = require("fs");
2+
const path = require('path')
3+
4+
let data = {}
5+
let dataDirectory = "app/data";
6+
let files = readdirSync(dataDirectory);
7+
8+
files.forEach((file) => {
9+
try {
10+
const name = path.parse(file).name
11+
const filepath = path.resolve(dataDirectory, file)
12+
13+
data[name] = JSON.parse(readFileSync(filepath, 'utf8'))
14+
} catch (err) {
15+
console.error(err)
16+
}
17+
});
18+
19+
module.exports = data

docker-compose.yml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
version: "3.8"
2+
3+
services:
4+
app:
5+
container_name: ${SERVER_NAME:-mock-json-server}
6+
build:
7+
context: .
8+
ports:
9+
- ${SERVER_PORT:-3000}:3000
10+
environment:
11+
- SERVER_PORT=${SERVER_PORT:-3000}
12+
- SERVER_PREFIX=${SERVER_PREFIX:-v1}
13+
volumes:
14+
- ./app:/usr/local/app
15+
healthcheck:
16+
test: wget --no-verbose --tries=1 --spider http://localhost:3000/healthcheck || exit 1
17+
interval: 60s
18+
retries: 1
19+
start_period: 20s
20+
timeout: 10s

index.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
const jsonServer = require('json-server')
2+
3+
let isAuthenticated = true;
4+
const data = require('./data.js')
5+
const routes = require('./app/routes.js')
6+
7+
const server = jsonServer.create()
8+
const router = jsonServer.router(data)
9+
const middlewares = jsonServer.defaults()
10+
11+
server.use(jsonServer.bodyParser);
12+
13+
// auth middleware
14+
server.use( function ( req, res, next ) {
15+
if (req.url == '/healthcheck') {
16+
res.status( 200 ).send( "ok" )
17+
} else {
18+
next()
19+
}
20+
})
21+
22+
server.use( function ( req, res, next ) {
23+
if (isAuthenticated) {
24+
next()
25+
} else {
26+
res.status( 401 ).send( "Unauthorized!" )
27+
}
28+
} );
29+
30+
// the logout endpoint
31+
server.get( '/logout', function ( req, res ) {
32+
isAuthenticated = false;
33+
res.status(200).send("logged out");
34+
} );
35+
36+
server.use(middlewares)
37+
38+
// merge routes into default prefix
39+
const prefix = `/${process.env.SERVER_PREFIX}/*`
40+
const defaultRoutes = {}
41+
defaultRoutes[prefix] = "/$1"
42+
43+
server.use(jsonServer.rewriter({...defaultRoutes, ...routes}));
44+
45+
46+
server.use(router)
47+
48+
// Avoid CORS issue
49+
// server.use( (req, res, next) => {
50+
// res.header("Access-Control-Allow-Origin", "*");
51+
// // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
52+
// next();
53+
// });
54+
55+
server.listen(3000, () => {
56+
console.log(`JSON Server is running, see http://localhost:${process.env.SERVER_PORT}`)
57+
})

json-server.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"host": "0.0.0.0"
3+
}

0 commit comments

Comments
 (0)