Skip to content

Commit

Permalink
feat: implement logger (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
adeherysh authored Apr 12, 2024
1 parent e02cb44 commit d41c3e0
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 60 deletions.
84 changes: 34 additions & 50 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ CLI tools for serve supple mock server with random fake data using <a href="http
## Features

* Using [Bun](https://github.com/oven-sh/bun)
* Using [Express.js](https://github.com/expressjs/express) for API routes
* Using [Express.js](https://github.com/expressjs/express)
* Written in [Typescript](https://github.com/microsoft/TypeScript)
* Random fake data using [Faker.js](https://github.com/faker-js/faker)
* Schema validation using JSON Schema
Expand Down Expand Up @@ -50,9 +50,27 @@ GET http://localhost:8080/?mock[response][body]={"ping":"pong"}
HTTP/1.1 200 OK
content-type: application/json
content-length: 15
content-length: 18
{"ping":"pong"}
{
ping: "pong"
}
```

Specify a search body param with random generate mock data using faker.js.

```http
GET http://localhost:8080/?mock[response][body]={"name":"{{person.fullName}}","avatar":"{{image.avatar}}"}
HTTP/1.1 200 OK
content-type: application/json
content-length: 87
{
name: "Allen Brown",
avatar: "https://avatars.githubusercontent.com/u/97165289"
}
```

### Status
Expand Down Expand Up @@ -98,53 +116,19 @@ Specify a search schema validation in json schema (stringify) to set request bod
GET http://localhost:8080/?mock[request][body][schema]=${{ stringify json schema }}
```

## Example Code
### Health check

```
async function getUsers() {
const queryParams = new URLSearchParams({
mock: {
response: {
body: {
api_code: 101000,
data: [
...(() => {
let items = [];
for (let i = 0; i < 10; i++) {
items.push({
id: 1,
username: "{{internet.userName}}",
email: "{{internet.email}}",
avatar: "{{image.avatar}}",
birthdate: "{{date.birthdate}}",
});
}
return items;
})()
],
meta: {
version: "v1.84.0",
api_status: "unstable",
api_env: "prod"
},
},
headers: {
"Content-Type": "application/json"
},
status: 200,
delay: 3000,
},
},
}).toString();
const response = await fetch(`http://localhost:8080/users?${queryParams}`, {
method: "GET",
headers: {
"X-Smocker-Secret": `${process.env.SMOCKER_SECRET_KEY}`,
},
});
const users = await response.json();
console.log(users);
Predefined health check route.

```http
GET http://localhost:8080/health-check
HTTP/1.1 200 OK
content-type: application/json
content-length: 24
{
health_check: "up"
}
```
44 changes: 40 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ CLI tools for serve supple mock server with random fake data using <a href="http
## Features

* Using [Bun](https://github.com/oven-sh/bun)
* Using [Express.js](https://github.com/expressjs/express) for API routes
* Using [Express.js](https://github.com/expressjs/express)
* Written in [Typescript](https://github.com/microsoft/TypeScript)
* Random fake data using [Faker.js](https://github.com/faker-js/faker)
* Schema validation using JSON Schema 7
Expand All @@ -17,7 +17,7 @@ CLI tools for serve supple mock server with random fake data using <a href="http
Setup smockr

```
$ npm install --global @ktbs/smockr
$ npm install -g @ktbs/smockr
```

## Quick Start
Expand All @@ -38,6 +38,7 @@ $ smockr \
--allowMethods "GET,POST,PATCH" \
--allowHeaders "Content-Type,Authorization"
```
When you define secret as a parameter, the client request must be include `X-Smockr-Secret` header with the same value

See a list of all available options

Expand All @@ -63,9 +64,27 @@ GET http://localhost:8080/?mock[response][body]={"ping":"pong"}
HTTP/1.1 200 OK
content-type: application/json
content-length: 15
content-length: 18
{"ping":"pong"}
{
ping: "pong"
}
```

Specify a search body param with random generate mock data using faker.js.

```http
GET http://localhost:8080/?mock[response][body]={"name":"{{person.fullName}}","avatar":"{{image.avatar}}"}
HTTP/1.1 200 OK
content-type: application/json
content-length: 87
{
name: "Allen Brown",
avatar: "https://avatars.githubusercontent.com/u/97165289"
}
```

### Status
Expand Down Expand Up @@ -110,3 +129,20 @@ Specify a search schema validation in json schema (stringify) to set request bod
```http
GET http://localhost:8080/?mock[request][body][schema]=${{ stringify json schema }}
```

### Health check

Predefined health check route.

```http
GET http://localhost:8080/health-check
HTTP/1.1 200 OK
content-type: application/json
content-length: 24
{
health_check: "up"
}
```
Binary file modified bun.lockb
Binary file not shown.
2 changes: 1 addition & 1 deletion commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import path from 'path'
* @usage {cliName} --port 8080
*
* @param {number} [port=8080] define port
* @param {string} [secret=""] define secret for client header X-Smocker-Secret
* @param {string} [secret=""] define secret for client header X-Smockr-Secret
* @param {string} [allowOrigin="*"] define allow cors origin
* @param {string} [allowMethods="GET,HEAD,PUT,PATCH,POST,DELETE"] define allow cors methods
* @param {string} [allowHeaders="*"] define allow cors headers
Expand Down
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
"api",
"mock",
"mocking",
"faker",
"fakerjs",
"bun",
"cli",
"tools",
Expand All @@ -54,6 +56,7 @@
"cors": "^2.8.5",
"express": "^4.19.2",
"json-schema": "^0.4.0",
"morgan": "^1.10.0",
"react": "^18",
"react-dom": "^18",
"zod": "^3.22.4"
Expand All @@ -65,6 +68,7 @@
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/json-schema": "^7.0.11",
"@types/morgan": "^1.9.9",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
Expand Down
17 changes: 12 additions & 5 deletions server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { parseSchema } from '@/utils/parsers/parseSchema'
import { faker } from '@faker-js/faker'
import cors from 'cors'
import express, { Request, Response } from 'express'
import morgan from 'morgan'
import pkg from './package.json'

const app = express()
Expand All @@ -11,7 +12,7 @@ const corsOptions = cors({
origin: process.env.ALLOWED_ORIGIN,
methods: process.env.ALLOWED_METHODS,
allowedHeaders: process.env.ALLOWED_HEADERS
? `X-Smocker-Secret,${process.env.ALLOWED_HEADERS}`
? `X-Smockr-Secret,${process.env.ALLOWED_HEADERS}`
: '*',
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
})
Expand All @@ -20,10 +21,16 @@ app.use(corsOptions)

app.use(express.json())

app.use(morgan('combined'))

app.get('/health-check', (_req: Request, res: Response) => {
res.send({ health_check: 'up' })
})

app.all('*', (req: Request, res: Response) => {
const { mock }: any = req.query
const appSecretKey = process.env.SECRET_KEY || ''
const secretKey = req.headers['X-Smocker-Secret'] || ''
const secretKey = req.headers['X-Smockr-Secret'] || ''
const bodySchema = mock?.request?.body?.schema
? JSON.parse(mock.request.body.schema.toString())
: undefined
Expand Down Expand Up @@ -52,9 +59,9 @@ app.all('*', (req: Request, res: Response) => {

if (
(!body && req.method === 'GET') ||
status < 100 ||
status > 599 ||
(bodySchema && !['PUT', 'POST', 'PATCH'].includes(req.method))
(bodySchema && !['PUT', 'POST', 'PATCH'].includes(req.method)) ||
status < 200 ||
status > 599
) {
res.status(422)
res.send({
Expand Down

0 comments on commit d41c3e0

Please sign in to comment.