React mock server with MirageJS — Part 2
React mock server with MirageJS — Part 1
Sample Project: https://github.com/xiao617/mirage-workshop
0. Define Type:
export interface TodoObject{
id: string,
name: string,
}
1. Models:
In MirageJS model is the place to define the schema.
models: {
todo: Model.extend<Partial<TodoObject>>({})
},
Here, we define a model “todo” and tell MirageJS its type is TodoObject.
Note: Partial means not all columns in TodoObject need to be provided. Other options are Required(Make all properties in Type required) and Readonly(Make all properties in Type read-only).
2. Factories
If we want to provide some initial value for our data, we can use factories.
factories: {
todo: Factory.extend<Partial<TodoObject>>({
get name() {
return `Listen to ${faker.music.genre()}`;
}
})
},
name is the property in our TodoObject.
Note: faker is a library that can help us generate fake data.
3. Seeds
We can provide some initial data.
seeds(server) {
server.create("todo", { name: "Buy Cookies" });
server.createList("todo", 3);
// if you did not provide init value factory will help you to generate some. server.db.loadData(JSON_FORMAT_DATA)
//you can load from json file
},
4. Routes
Typescript version usage:
routes() {
//this.urlPrefix = "YOU_PREFIX";
this.get("/todos", (schema, request) => {
return schema.all("todo");
});
this.post("/todos", (schema, request) => {
let attrs = JSON.parse(request.requestBody);
schema.create("todo", attrs);
return schema.all("todo");
});
this.del("/todos/:key", (schema, request) => {
let keyid = request.params.key;
let post = schema.findBy("todo", {id: keyid})
if(post !== null)
post.destroy();
return schema.all("todo");
});
}
Thanks for reading! This is the basic usage for TypeScript with MirageJS