mirror of
https://github.com/typicode/json-server.git
synced 2025-07-28 12:43:18 +08:00
Refactor
This commit is contained in:
@ -3,6 +3,7 @@
|
||||
## Unreleased
|
||||
|
||||
* Improve performances
|
||||
* Add `Location` header to newly created resources [#473](https://github.com/typicode/json-server/pull/473)
|
||||
|
||||
## [0.9.5][2016-02-11]
|
||||
|
||||
|
10
src/server/router/get-full-url.js
Normal file
10
src/server/router/get-full-url.js
Normal file
@ -0,0 +1,10 @@
|
||||
const url = require('url')
|
||||
|
||||
module.exports = function getFullURL (req) {
|
||||
const root = url.format({
|
||||
protocol: req.protocol,
|
||||
host: req.get('host')
|
||||
})
|
||||
|
||||
return `${root}${req.originalUrl}`
|
||||
}
|
@ -1,8 +1,8 @@
|
||||
const url = require('url')
|
||||
const express = require('express')
|
||||
const _ = require('lodash')
|
||||
const pluralize = require('pluralize')
|
||||
const write = require('./write')
|
||||
const getFullURL = require('./get-full-url')
|
||||
const utils = require('../utils')
|
||||
|
||||
module.exports = (db, name) => {
|
||||
@ -34,15 +34,6 @@ module.exports = (db, name) => {
|
||||
})
|
||||
}
|
||||
|
||||
function getFullURL (req) {
|
||||
const root = url.format({
|
||||
protocol: req.protocol,
|
||||
host: req.get('host')
|
||||
})
|
||||
|
||||
return `${root}${req.originalUrl}`
|
||||
}
|
||||
|
||||
// GET /name
|
||||
// GET /name?q=
|
||||
// GET /name?attr=&attr=
|
||||
@ -250,7 +241,8 @@ module.exports = (db, name) => {
|
||||
.value()
|
||||
|
||||
res.setHeader('Access-Control-Expose-Headers', 'Location')
|
||||
res.setHeader('Location', getFullURL(req) + '/' + resource.id)
|
||||
res.location(`${getFullURL(req)}/${resource.id}`)
|
||||
|
||||
res.status(201)
|
||||
res.locals.data = resource
|
||||
|
||||
|
@ -1,5 +1,6 @@
|
||||
const express = require('express')
|
||||
const write = require('./write')
|
||||
const getFullURL = require('./get-full-url')
|
||||
|
||||
module.exports = (db, name) => {
|
||||
const router = express.Router()
|
||||
@ -12,6 +13,10 @@ module.exports = (db, name) => {
|
||||
function create (req, res, next) {
|
||||
db.set(name, req.body).value()
|
||||
res.locals.data = db.get(name).value()
|
||||
|
||||
res.setHeader('Access-Control-Expose-Headers', 'Location')
|
||||
res.location(`${getFullURL(req)}`)
|
||||
|
||||
res.status(201)
|
||||
next()
|
||||
}
|
||||
|
@ -506,7 +506,8 @@ describe('Server', () => {
|
||||
request(server)
|
||||
.post('/posts')
|
||||
.send({body: 'foo', booleanValue: true, integerValue: 1})
|
||||
.expect('Location', /3$/)
|
||||
.expect('Access-Control-Expose-Headers', 'Location')
|
||||
.expect('Location', /posts\/3$/)
|
||||
.expect('Content-Type', /json/)
|
||||
.expect({id: 3, body: 'foo', booleanValue: true, integerValue: 1})
|
||||
.expect(201)
|
||||
|
Reference in New Issue
Block a user