Allows for alternate foreign key attribute names, eg snake case (post_id). Defaults to 'Id' (#556)

This commit is contained in:
Benjamin Bruneau
2017-06-27 14:28:34 -04:00
committed by typicode
parent 02c3ea936e
commit f1d7677d01
5 changed files with 17 additions and 9 deletions

View File

@ -63,6 +63,11 @@ module.exports = function () {
description: 'Set database id property (e.g. _id)',
default: 'id'
},
foreignKeySuffix: {
alias: 'f',
description: 'Set foreign key suffix, (e.g. _id as in post_id)',
default: 'Id'
},
quiet: {
alias: 'q',
description: 'Suppress log messages from output'

View File

@ -42,9 +42,8 @@ function createApp (source, object, routes, middlewares, argv) {
try {
router = jsonServer.router(
is.JSON(source)
? source
: object
is.JSON(source) ? source : object,
argv
)
} catch (e) {
console.log()

View File

@ -11,7 +11,7 @@ const nested = require('./nested')
const singular = require('./singular')
const mixins = require('../mixins')
module.exports = (source) => {
module.exports = (source, argv) => {
// Create router
const router = express.Router()
@ -60,7 +60,7 @@ module.exports = (source) => {
}
if (_.isArray(value)) {
router.use(`/${key}`, plural(db, key))
router.use(`/${key}`, plural(db, key, argv))
return
}

View File

@ -5,7 +5,7 @@ const write = require('./write')
const getFullURL = require('./get-full-url')
const utils = require('../utils')
module.exports = (db, name) => {
module.exports = (db, name, argv) => {
// Create router
const router = express.Router()
@ -16,7 +16,7 @@ module.exports = (db, name) => {
if (db.get(externalResource).value) {
const query = {}
const singularResource = pluralize.singular(name)
query[`${singularResource}Id`] = resource.id
query[`${singularResource}${argv.foreignKeySuffix}`] = resource.id
resource[externalResource] = db.get(externalResource).filter(query).value()
}
})
@ -28,7 +28,7 @@ module.exports = (db, name) => {
.forEach((innerResource) => {
const plural = pluralize(innerResource)
if (db.get(plural).value()) {
const prop = `${innerResource}Id`
const prop = `${innerResource}${argv.foreignKeySuffix}`
resource[innerResource] = db.get(plural).getById(resource[prop]).value()
}
})

View File

@ -15,6 +15,10 @@ describe('Server', () => {
'/articles?_id=:id': '/posts/:id'
}
const defaultArgv = {
foreignKeySuffix: 'Id'
}
beforeEach(() => {
db = {}
@ -92,7 +96,7 @@ describe('Server', () => {
]
server = jsonServer.create()
router = jsonServer.router(db)
router = jsonServer.router(db, defaultArgv)
server.use(jsonServer.defaults())
server.use(jsonServer.rewriter(rewriterRules))
server.use(router)