1.0.7 • Published 6 years ago
fake-json-api v1.0.7
Fake JSON API
A small package that intercepts AJAX requests and responds with data stored locally in IndexedDB. It attempts to fake an actual JSON API.
Setup
Install the package:
npm i fake-json-apior
yarn add fake-json-apiImport it in your code:
import api from 'fake-json-api'or
const api = require('fake-json-api')Configure the database:
api.configure({
posts: {
schema: '++id,title,content'
}
})Uses Dexie.js stores syntax to define the schema
Add some data:
api.loaddata({
posts: [
{ id: 1, title: 'Test post 1', content: 'blah blah blah' },
{ id: 2, title: 'Test post 2', content: 'blah blah blah' }
]
})Start it intercepting requests:
api.listen()Make a request:
fetch(/posts)
.then(res => res.json())
.then(data => console.log(res.data))Available endpoints would be:
- GET
/posts - POST
/posts - GET
/posts/:id - PUT
/posts/:id - DELETE
/posts/:id
Relational data
Works with dexie-relationships for relational data. So for example if you want to add users to posts:
api.configure({
posts: {
schema: '++id,title,content,user_id -> users.id',
populate: { user: 'user_id' }
},
user: {
schema: '++id,username',
populate: { posts: 'posts' }
}
})
api.loaddata({
posts: [
{ id: 1, title: 'Test post 1', content: 'blah blah blah', user_id: 1 },
{ id: 2, title: 'Test post 2', content: 'blah blah blah', user_id: 2 }
],
users: [
{ id: 1, username: 'mickyginger' },
{ id: 2, username: 'mattstuddert' }
]
})Users would now be nested in posts, and each user object would have an array of nested posts.
Available endpoints would be:
- GET
/posts - POST
/posts - GET
/posts/:id - PUT
/posts/:id - DELETE
/posts/:id
- GET
/users - POST
/users - GET
/users/:id - PUT
/users/:id - DELETE
/users/:id