Skip to content

Commit

Permalink
[email protected] into main ☄️
Browse files Browse the repository at this point in the history
[email protected] into main ☄️
  • Loading branch information
debabin authored Mar 4, 2023
2 parents c0a85c7 + 8fd39a0 commit ce22a42
Show file tree
Hide file tree
Showing 84 changed files with 4,706 additions and 1,145 deletions.
14 changes: 7 additions & 7 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,18 @@
{
"files": ["*.ts"],
"parserOptions": {
"project": ["./tsconfig.json"]
"project": ["./tsconfig.dev.json"]
}
}
],
"plugins": ["@typescript-eslint", "simple-import-sort", "prettier"],
"rules": {
"no-await-in-loop": "off",
"no-shadow": "off",
"import/no-extraneous-dependencies": "off",
"@typescript-eslint/no-shadow": "off",
"require-await": "off",
"@typescript-eslint/require-await": "error",
"import/no-extraneous-dependencies": "off",
"import/prefer-default-export": "off",
"simple-import-sort/imports": [
"error",
{
Expand All @@ -36,9 +38,7 @@
]
}
],
"simple-import-sort/exports": "error",
"import/prefer-default-export": "off",
"consistent-return": "off"
"simple-import-sort/exports": "error"
},
"ignorePatterns": ["jest.config.js", "mock-server.config.js"]
"ignorePatterns": ["jest.config.js"]
}
158 changes: 111 additions & 47 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ $ yarn add mock-config-server --dev
## Features

- **TypeScript support out of the box** - full typed package
- **Full Rest Api support** - using simple configs of a certain format, you can easily simulate the operation of servers
- **Full Rest Api support** - using simple configs of a certain format, you can easily simulate rest operation of servers
- **GraphQL support** - using simple configs of a certain format, you can easily simulate graphlql operation of servers
- **CORS setup** - turn on and off CORS, fully customizable when CORS is turned on
- **Support for any kind of static** - server can return any type of static file if needed. Images, HTML, CSS, JSON, etc

Expand All @@ -36,15 +37,18 @@ $ yarn add mock-config-server --dev
Create a `mock-server.config.js` file with server configuration

```javascript
/** @type {import('mock-config-server').Mock.ServerConfig} */
/** @type {import('mock-config-server').MockServerConfig} */
const mockServerConfig = {
configs: [
{
path: '/user',
method: 'get',
routes: [{ data: { emoji: '🦁', name: 'Nursultan' } }]
}
]
rest: {
baseUrl: '/api',
configs: [
{
path: '/user',
method: 'get',
routes: [{ data: { emoji: '🦁', name: 'Nursultan' } }]
}
]
}
};

export default mockServerConfig;
Expand All @@ -60,7 +64,12 @@ $ npx mock-config-server

## 🎭 Parameters for mock-server.config.(js|ts)

- `configs` {Array<RequestConfig>} configs for mock requests, [read](#configs)
- `rest?` Rest configs for mock requests
- `baseUrl?` {string} part of the url that will be substituted at the beginning of rest request url (default: `'/'`)
- `configs` {Array<RestRequestConfig>} configs for mock requests, [read](#configs)
- `graphql?` GraphQL configs for mock requests
- `baseUrl?` {string} part of the url that will be substituted at the beginning of graphql request url (default: `'/'`)
- `configs` {Array<GraphQLRequestConfig>} configs for mock requests, [read](#configs)
- `staticPath?` {StaticPath} entity for working with static files, [read](#static-path)
- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
- `cors?` {Cors} CORS settings object (default: `CORS is turn off`), [read](#cors)
Expand All @@ -69,57 +78,102 @@ $ npx mock-config-server

### Configs

Configs are the fundamental part of the mock server. These configs are easy to fill and maintain. Config entities is an object with which you can emulate various application behaviors. You can specify `headers` | `query` | `params` | `body` to define what contract data you need to get. Using this mechanism, you can easily simulate the operation of the server and emulate various cases
Configs are the fundamental part of the mock server. These configs are easy to fill and maintain. Config entities is an object with which you can emulate various application behaviors. You can specify `headers` | `query` | `params` | `body` for Rest request or `headers` | `query` | `variables` for GraphQL request to define what contract data you need to get. Using this mechanism, you can easily simulate the operation of the server and emulate various cases

##### request config
##### Rest request config

- `path` {string | RegExp} request path
- `method` {GET | POST | DELETE | PUT | PATCH} rest api method
- `routes` {RouteConfig} request routes
- `routes` {RestRouteConfig[]} request routes
- `data` {any} mock data of request
- `entities?` Object<headers | query | params | body> object that helps in data retrieval
- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)

##### route config
##### GraphQL request config

- `data` {any} mock data of request
- `entities?` Object<headers | query | params | body> object that helps in data retrieval
- `operationType` {query | mutation} graphql operation type
- `operationName` {string} graphql operation name
- `routes` {GraphQLRouteConfig[]} request routes
- `data` {any} mock data of request
- `entities?` Object<headers | query | variables> object that helps in data retrieval
- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)

##### entities
##### Rest example

```javascript
/** @type {import('mock-config-server').MockServerConfig} */
const mockServerConfig = {
rest: {
baseUrl: '/api',
configs: [
{
path: '/user',
method: 'get',
routes: [
{
entities: {
headers: { 'name-header': 'Nursultan' }
},
data: { emoji: '🦁', name: 'Nursultan' }
},
{
entities: {
headers: { 'name-header': 'Dmitriy' }
},
data: { emoji: '', name: 'Dmitriy' }
}
]
}
]
}
};

module.exports = mockServerConfig;
```

```typescript
interface Entities {
headers?: { [string]: string | number };
query?: { [string]: string | number };
params?: { [string]: string | number };
body?: any;
}
Now you can make a request with an additional header and get the desired result

```javascript
fetch('http://localhost:31299/api/user', {
headers: {
'name-header': 'Nursultan',
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((data) => console.log(data)); // { emoji: '🦁', name: 'Nursultan' }
```

##### Example
##### GraphQL example

```javascript
/** @type {import('mock-config-server').MockServerConfig} */
const mockServerConfig = {
configs: [
{
path: '/user',
method: 'get',
routes: [
{
entities: {
headers: { 'name-header': 'Nursultan' }
},
data: { emoji: '🦁', name: 'Nursultan' }
},
{
entities: {
headers: { 'name-header': 'Dmitriy' }
graphql: {
baseUrl: '/graphql',
configs: [
{
operationType: 'query',
operationName: 'GetUser',
routes: [
{
entities: {
headers: { 'name-header': 'Nursultan' }
},
data: { emoji: '🦁', name: 'Nursultan' }
},
data: { emoji: '', name: 'Dmitriy' }
}
]
}
]
{
entities: {
headers: { 'name-header': 'Dmitriy' }
},
data: { emoji: '', name: 'Dmitriy' }
}
]
}
]
}
};

module.exports = mockServerConfig;
Expand All @@ -128,8 +182,17 @@ module.exports = mockServerConfig;
Now you can make a request with an additional header and get the desired result

```javascript
fetch('http://localhost:31299/user', {
headers: { 'name-header': 'Nursultan' }
const body = JSON.stringify({
query: 'query GetUser { name }'
});

fetch('http://localhost:31299/graphql', {
method: 'POST',
headers: {
'name-header': 'Nursultan',
'Content-Type': 'application/json'
},
body
})
.then((response) => response.json())
.then((data) => console.log(data)); // { emoji: '🦁', name: 'Nursultan' }
Expand All @@ -151,7 +214,8 @@ Object with settings for [CORS](https://developer.mozilla.org/en-US/docs/Web/HTT

- `origin` {string | RegExp | Array<string | RegExp> | Function | Promise } available origins from which requests can be made
- `methods?` {Array<GET | POST | DELETE | PUT | PATCH>} available methods (default: `*`)
- `headers?` {Array<string>} available methods (default: `*`)
- `allowedHeaders?` {Array<string>} allowed headers (default: `*`)
- `exposedHeaders?` {Array<string>} exposed headers (default: `*`)
- `credentials?` {boolean} param tells browsers whether to expose the response to the frontend JavaScript code (default: `true`)
- `maxAge?` {number} how long the results can be cached (default: `3600`)

Expand Down
6 changes: 4 additions & 2 deletions bin/mock-config-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import * as fs from 'fs';

import { startMockServer } from '../src';

import { validateMockServerConfig } from './validateMockServerConfig/validateMockServerConfig';
import { resolveExportsFromSourceCode } from './resolveExportsFromSourceCode';

const start = async () => {
Expand Down Expand Up @@ -40,9 +41,10 @@ const start = async () => {
throw new Error('Cannot handle exports of mock-server.config.(ts|js)');
}

validateMockServerConfig(mockServerConfigExports.default);
startMockServer(mockServerConfigExports.default);
} catch (e: any) {
console.error(e.message);
} catch (error: any) {
console.error(error.message);
}
};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { validateBaseUrl } from './validateBaseUrl';

describe('validateBaseUrl', () => {
test('Should correctly handle baseUrl only with correct type', () => {
const correctBaseUrls = ['/stringWithLeadingSlash', undefined];
correctBaseUrls.forEach((correctBaseUrl) => {
expect(() => validateBaseUrl(correctBaseUrl)).not.toThrow(Error);
});

const incorrectBaseUrls = ['stringWithoutLeadingSlash', true, 3000, null, {}, [], () => {}];
incorrectBaseUrls.forEach((incorrectBaseUrl) => {
expect(() => validateBaseUrl(incorrectBaseUrl)).toThrow(new Error('baseUrl'));
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const validateBaseUrl = (baseUrl: unknown) => {
if (typeof baseUrl !== 'string' && typeof baseUrl !== 'undefined') {
throw new Error('baseUrl');
}
if (typeof baseUrl === 'string' && !baseUrl.startsWith('/')) {
throw new Error('baseUrl');
}
};
Loading

0 comments on commit ce22a42

Please sign in to comment.