mirror of
https://github.com/typicode/json-server.git
synced 2025-07-29 13:14:12 +08:00
Handle string/hash based ids
This commit is contained in:
@ -17,6 +17,7 @@
|
||||
"lowdb": "^0.5.1",
|
||||
"method-override": "^2.1.2",
|
||||
"morgan": "^1.3.1",
|
||||
"node-uuid": "^1.4.2",
|
||||
"serve-static": "^1.6.1",
|
||||
"superagent": "^0.15.7",
|
||||
"underscore": "^1.5.2",
|
||||
|
15
src/utils.js
15
src/utils.js
@ -1,4 +1,5 @@
|
||||
var _ = require('underscore')
|
||||
var uuid = require('node-uuid')
|
||||
var _inflections = require('underscore.inflections')
|
||||
_.mixin(_inflections)
|
||||
|
||||
@ -19,14 +20,22 @@ function toNative(value) {
|
||||
return value
|
||||
}
|
||||
|
||||
// Creates incremental id.
|
||||
// Return incremented id or uuid
|
||||
function createId(coll) {
|
||||
if (_.isEmpty(coll)) {
|
||||
return 1
|
||||
} else {
|
||||
return _.max(coll, function(doc) {
|
||||
var id = _.max(coll, function(doc) {
|
||||
return doc.id
|
||||
}).id + 1
|
||||
}).id
|
||||
|
||||
if (_.isFinite(id)) {
|
||||
// Increment integer id
|
||||
return ++id
|
||||
} else {
|
||||
// Generate string id
|
||||
return uuid()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -29,6 +29,10 @@ describe('Server', function() {
|
||||
{id: 5, published: false, postId: 2},
|
||||
]
|
||||
|
||||
db.refs = [
|
||||
{id: 'abcd-1234', url: 'http://example.com', postId: 1}
|
||||
]
|
||||
|
||||
server = jsonServer(db)
|
||||
})
|
||||
|
||||
@ -166,7 +170,8 @@ describe('Server', function() {
|
||||
|
||||
|
||||
describe('POST /:resource', function() {
|
||||
it('should respond with json and create a resource', function(done) {
|
||||
it('should respond with json, create a resource and increment id',
|
||||
function(done) {
|
||||
request(server)
|
||||
.post('/posts')
|
||||
.send({body: 'foo', booleanValue: 'true', integerValue: '1'})
|
||||
@ -179,6 +184,20 @@ describe('Server', function() {
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should respond with json, create a resource and generate string id',
|
||||
function(done) {
|
||||
request(server)
|
||||
.post('/refs')
|
||||
.send({url: 'http://foo.com', postId: '1'})
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(200)
|
||||
.end(function(err, res){
|
||||
if (err) return done(err)
|
||||
assert.equal(db.refs.length, 2)
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /:resource/:id', function() {
|
||||
|
@ -24,7 +24,7 @@ describe('utils', function() {
|
||||
{ name: 'comments', id: 3 }
|
||||
]
|
||||
|
||||
assert.deepEqual(expected, utils.getRemovable(db))
|
||||
assert.deepEqual(utils.getRemovable(db), expected)
|
||||
|
||||
})
|
||||
})
|
||||
|
Reference in New Issue
Block a user