PrototypedJS
An API mocking library to help prototype frontends applications without worrying about the backend.
Often times UI developers find themselves wanting to build a UI only to realize they do not have a backend API with data. In these situations, developers use hard coded mock data stored in JSON files or even simple JS/TS files. This works initially, however, once the backend API is ready, the UI needs rewriting to account for the Promise based responses the API returns. This results in a gap to go from prototyping to production. PrototypedJS helps bridge this gap by creating a promise based API that developers can use instead of actual API calls. If done right, the application can be run in "DEV" mode and"PROD" mode where they use PrototypedJS in "DEV" mode and the actual API in "PROD".
Bonus Tip: PrototypedJS can be used for mocking APIs in unit tests.
The code can be found at PrototypedJS Github
Package is published on npm at PrototypedJS on NPM
Installation
npm install @prototypedjs/core
OR
yarn add @prototypedjs/core
Initializing
import { createApi } from '@prototypedjs/core';
interface User {
id: string;
name: string;
email: string;
}
const userApi = createApi<User>();
The userApi object can be used as an abstraction for the backend. It has methods that use the Promise API to handle data.
const allUsers = await userApi.all();
const newUser = await userApi.post({
id: '1',
name: 'John Doe',
email: 'john.doe@iamadonut.com',
});
// This is a custom filter function for the User interface.
const getUser = (id: string) => (user: User) => user.id === id;
const oneUser = await userApi.get(getUser('1'));
const updateUser = await userApi.put(getUser('1'), { name: 'Jane Doe' });
const deletedUser = await userApi.remove(getUser('1'));
Working with Initial Mock Data
If you have initial mock data that you want to use, it can be passed in while creating the API object.
const mockUsers: User[] = [{
id: '1',
name: 'Jane Doe',
email: 'jane.doe@iamadonut.com',
}];
const userApi = createApi<User>(mockUsers);
The API object will add the mock data to its internal storage.
const users = await userApi.all(); // users.length = 1