I have two Models in MirageJs:
Each blog could have more tags and vice versa. I made a many-to-many relationship with a join table called blog_tag
. My problem is, when I get the response from the server, the tags only contains the id properties. How could I embed the whole tag object into the response?
Response:
{
"blogs": [
{
"title": "Some title",
"author": "Author 0",
"id": "1",
"tags": [
{
"id": "1"
// Other properties are not included here :(
}
]
}
]
}
I like to see something like this:
{
"blogs": [
{
"title": "Some title",
"author": "Author 0",
"id": "1",
"tags": [
{
"id": "1",
"name": "Tag 0"
}
]
}
]
}
My server config: Mirage REPL
import { belongsTo, createServer, Factory, hasMany, Model, RestSerializer } from "miragejs"
export default createServer({
serializers: {
blog: RestSerializer.extend({
include: ['tags'],
embed: true
})
},
models: {
blog: Model.extend({
tags: hasMany('blog_tag')
}),
tag: Model.extend({
blogs: hasMany('blog_tag')
}),
blog_tag: Model.extend({
blog: belongsTo(),
tag: belongsTo()
})
},
factories: {
blog: Factory.extend({
author(i) {
return 'Author ' + i
},
title() {
return 'Some title'
}
}),
tag: Factory.extend({
name(i) {
return 'Tag ' + i
}
})
},
seeds(server) {
server.createList('blog', 2)
server.createList('tag', 10)
server.create('blog_tag', { blogId: 1, tagId: 1 })
},
routes() {
this.namespace = "api"
this.get("/blogs", (schema) => {
return schema.blogs.all()
})
},
})
You actually don't need the blog_tag
model to be able to do many-to-many, Mirage.js will manage with just the blog
and tag
models.
See a working example here : Mirage REPL