使用路由缩写同样可以完成新建或者编辑数据。这也是一个标准的路由,它使用请求体中的一个属性 movie 来创建一条新的数据:
1 2 3 4 5
this.post('/movies', (schema, request) => { let attrs = JSON.parse(request.requestBody).movie
return schema.movies.create(attrs) })
同样的工作也可以使用缩写来完成:
1
this.post('/movies')
路由缩写使用基于 HTTP 动词的默认状态码:
GET, PATCH/PUT, DEL 200
POST 201
路由缩写:GET 方法(GET Shorthands)
获取集合:
1 2 3 4 5 6 7 8
// Shorthand this.get("/contacts") // finds type by singularizing url this.get("/contacts", "users") // optionally specify the collection as second param
// equivalent this.get("/contacts", (schema) => { return schema.contacts.all() // users in the second case })
// Shorthand this.get("/contacts/:id") // finds type by singularizing url this.get("/contacts/:id", "user") // optionally specify the type as second param
// equivalent this.get("/contacts/:id", (schema, request) => { let id = request.params.id
return schema.contacts.find(id) // users in the second case })
return contacts.find(ids) // users in the second case })
路由缩写:POST 方法(POST Shorthands)
创建资源:
1 2 3 4 5 6 7 8 9 10
// Shorthand this.post("/contacts") // finds type by singularizing url this.post("/contacts", "user") // optionally specify the type as second param
// equivalent this.post("/contacts", function (schema, request) { let attrs = this.normalizedRequestAttrs()
return schema.contacts.create(attrs) })
注意,要使 POST/PATCH/PUT 缩写生效,Mirage 需要知道应用发送的请求中所使用的 JSON 是哪一种格式,以便 POST 缩写可以用正确的方式将数据插入库中。
更详细的信息请看 serializer部分中 normalize 的内容。
路由缩写:PATCH/PUT 方法(PATCH/PUT Shorthands)
更新资源:
1 2 3 4 5 6 7 8 9 10 11
// Shorthand (these also work with this.put) this.patch("/contacts/:id") // finds type by singularizing url this.patch("/contacts/:id", "user") // optionally specify the type as second param
// equivalent this.patch("/contacts/:id", function (schema, request) { let id = request.params.id let attrs = this.normalizedRequestAttrs()
return schema.contacts.find(id).update(attrs) })
路由缩写:DELETE 方法(DELETE Shorthands)
删除(destroying)资源:
1 2 3 4 5 6 7 8 9 10
// Shorthand this.del("/contacts/:id") // finds type by singularizing url this.del("/contacts/:id", "user") // optionally specify the type as second param
// equivalent this.del("/contacts/:id", (schema, request) => { let id = request.params.id
评论