A small utility to fast create typed mock servers.
You can use this utility to test your React (or other framework) components without the need of a backend server.
It wraps msw, so you can refer to the documentation here.
FakerJS is used under the hood to provide data generation, full documentation here.
- Small and lightweight
- Built-in Typescript support
- Works with all javascript frameworks
- Create a full queryable database with:
- generated fake data (thanks to FakerJS)
- your data (json, text, and so on...)
npm install -s msw ts-mckr
or
yarn add msw ts-mckr
or
pnpm install msw ts-mckr
As said here this utility is essentially a msw wrap, so to work the Service Worker needs to be create. To do so, just run:
npx msw init ./public --save
or
pnpx msw init ./public --save
// Import
import dbUtils, { MockServer, MockServerInit } from 'ts-mckr';
// Import static data
import quotes from './quotes.json';
// Database creation
const mockDb = {
quotes: {
id: dbUtils.primaryKey(Number),
quote: String,
author: String,
},
users: {
id: dbUtils.primaryKey(Number),
name: String,
},
};
const handlers = new MockServer()
// Database init
.createDB(mockDb)
// Dataset injection, using fake data
.createDataSet(
{
users: [
{
// name: 'John Doe', or
name: MockServer.getFakeData({ module: 'name', method: 'fullName', language: 'it' }),
birthDate: MockServer.getFakeData({ module: 'date', method: 'birthdate' }),
/* or with object declaration (not recommended)
👇 we need this to get faker methods, if you have better solution, please create a pull request.
name: <FakerData<'name'>>{ module: 'name', method: 'fullName', language: 'it' },
birthDate: <FakerData<'date'>>{ module: 'date', method: 'birthdate' },
*/
},
],
},
// Dataset options
{ repeat: 40 }
)
// Dataset injection, using json data (static)
.createDataSet({ quotes })
// Get handlers (get, post, ecc...)
.createHandlers();
// Create worker
const worker = MockServerInit(...handlers);
// Use worker previously init
await worker.start({ onUnhandledRequest: 'bypass' });
interface DummyUsers {
id: number;
name: string;
birthDate: string;
}
// Create api endpoint, params will contains filter and pagination data
const listUsers = (params?: object) =>
axiosInstance.get<unknown, ViewData<DummyUsers>>('/users', {
params: { ...params, delay: 250 },
});
type | default | required | |
---|---|---|---|
repeat | number | 1 | ❌ |
autoIncrement | boolean | true | ❌ |