Skip to content

Commit e28d82a

Browse files
committed
feat: Add support for custom 'params' property name (e.g. from default req.params to req.myOwnWhateverProp)
1 parent 2f4c0bb commit e28d82a

File tree

2 files changed

+103
-14
lines changed

2 files changed

+103
-14
lines changed

src/index.js

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -265,32 +265,33 @@ const createEndpoint = (args, verb) => {
265265
if (!args || !args.length)
266266
throw new Error(`Missing required argument. Impossible to create an ${httpVerb} endpoint without any argument. Pass at least one function similar to (req, res) => ...`)
267267

268-
const firstArgType = typeof(args[0])
269-
const firstArgIsArray = firstArgType == 'object' && args[0].length != undefined
268+
const firstArgument = args[0]
269+
const firstArgType = typeof(firstArgument)
270+
const firstArgIsArray = firstArgType == 'object' && firstArgument.length != undefined
270271
// Case 1 - Single arguments. It must be a function
271272
if (args.length == 1) {
272273
if (firstArgType != 'function' && firstArgType != 'string' && !firstArgIsArray)
273274
throw new Error(`Wrong argument exception. When only one argument is passed to an ${httpVerb} endpoint, then that argument must be either be a string (endpoint path), an array of strings (collection of endpoint path) or a function similar to (req, res) => ...`)
274275

275-
if (firstArgIsArray && args[0].some(x => typeof(x) != 'string'))
276+
if (firstArgIsArray && firstArgument.some(x => typeof(x) != 'string'))
276277
throw new Error(`Wrong argument exception. When the first argument passed to create an ${httpVerb} endpoint is an array, that array must be made of string only.`)
277278

278279
_endpoints.push({
279-
routes: getRouteDetails(firstArgType == 'function' ? '/' : args[0]),
280+
routes: getRouteDetails(firstArgType == 'function' ? '/' : firstArgument),
280281
method: verb,
281-
execute: (req, res) => executeHandlers(req, res, [fnToPromise(args[0])])
282+
execute: (req, res) => executeHandlers(req, res, [fnToPromise(firstArgType != 'string' ? firstArgument : () => null)])
282283
})
283284
}
284285
// Case 2 - Two or more arguments. Unless the first argument is a path ('string'), then they should all be functions
285286
else {
286-
const firstArgType = typeof(args[0])
287-
const firstArgIsArray = firstArgType == 'object' && args[0].length != undefined
287+
const firstArgType = typeof(firstArgument)
288+
const firstArgIsArray = firstArgType == 'object' && firstArgument.length != undefined
288289
let p, handlerFns, idxOffset
289290
if (firstArgType == 'string' || firstArgIsArray) {
290291
[p, ...handlerFns] = args
291292
idxOffset = 2
292293

293-
if (firstArgIsArray && args[0].some(x => typeof(x) != 'string'))
294+
if (firstArgIsArray && firstArgument.some(x => typeof(x) != 'string'))
294295
throw new Error(`Wrong argument exception. When the first argument passed to create an ${httpVerb} endpoint is an array, that array must be made of string only.`)
295296
}
296297
else {
@@ -336,6 +337,13 @@ const processEvent = (req, res, config={}, endpoints=[], handlers=[], requiredHe
336337
req.__receivedTime = Date.now()
337338
req.__transactionId = shortid.generate().replace(/-/g, 'r').replace(/_/g, '9')
338339
req.__ellapsedMillis = () => Date.now() - req.__receivedTime
340+
let { propName:paramsPropName='params', paramsMode=null } = config.params || {}
341+
// Ensure backward compatibility with version 0.12.1-alpha.0
342+
if (config.paramsMode && !paramsMode)
343+
paramsMode = config.paramsMode
344+
345+
if (!req[paramsPropName] || typeof(req[paramsPropName]) != 'object')
346+
req[paramsPropName] = {}
339347

340348
// 1. Make sure the pre and post event methods exist
341349
if (!preEvent)
@@ -380,15 +388,13 @@ const processEvent = (req, res, config={}, endpoints=[], handlers=[], requiredHe
380388
return res.status(404).send(`Endpoint '${pathname}' for method ${httpMethod} not found.`)
381389

382390
// 5.4. Extract all params from that request, including both the url route params and the payload params.
383-
const paramsMode = PARAMSMODE[config.paramsMode] ? config.paramsMode : 'all'
384-
const paramts = paramsMode == 'all' || paramsMode == 'route' ? Object.assign({}, endpoint.winningRoute.parameters) : {}
385-
const getParams = paramsMode == 'all' || paramsMode == 'body' ? reqUtil.getParams(req) : Promise.resolve({})
391+
const validParamsMode = PARAMSMODE[paramsMode] ? paramsMode : 'all'
392+
const paramts = validParamsMode == 'all' || validParamsMode == 'route' ? Object.assign({}, endpoint.winningRoute.parameters) : {}
393+
const getParams = validParamsMode == 'all' || validParamsMode == 'body' ? reqUtil.getParams(req) : Promise.resolve({})
386394
return getParams.then(parameters => Object.assign(parameters, paramts))
387395
.then(parameters => {
388396
// 5.5. Add all paramaters to the request object
389-
if (!req.params || typeof(req.params) != 'object')
390-
req.params = {}
391-
Object.assign(req.params, parameters || {})
397+
Object.assign(req[paramsPropName], parameters || {})
392398
// 5.6. Process all global handlers
393399
return executeHandlers(req, res, handlers)
394400
// 5.8. Process the endpoint

test/index.js

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1283,3 +1283,86 @@ describe('app', () =>
12831283

12841284
return Promise.all([result_01, result_02])
12851285
})))
1286+
1287+
/*eslint-disable */
1288+
describe('app', () =>
1289+
describe('#handleEvent: 27', () =>
1290+
it(`Should support custom 'params' property name (e.g. from the default req.params to your req.myOwnWhatever ).`, () => {
1291+
/*eslint-enable */
1292+
const req_01 = httpMocks.createRequest({
1293+
method: 'GET',
1294+
headers: {
1295+
origin: 'http://localhost:8080',
1296+
referer: 'http://localhost:8080'
1297+
},
1298+
_parsedUrl: {
1299+
pathname: '/users/nicolas'
1300+
}
1301+
})
1302+
const res_01 = httpMocks.createResponse()
1303+
1304+
const req_02 = httpMocks.createRequest({
1305+
method: 'GET',
1306+
headers: {
1307+
origin: 'http://localhost:8080',
1308+
referer: 'http://localhost:8080'
1309+
},
1310+
_parsedUrl: {
1311+
pathname: '/users/nicolas'
1312+
},
1313+
query: { lastname: 'dao' }
1314+
})
1315+
const res_02 = httpMocks.createResponse()
1316+
1317+
const req_03 = httpMocks.createRequest({
1318+
method: 'GET',
1319+
headers: {
1320+
origin: 'http://localhost:8080',
1321+
referer: 'http://localhost:8080'
1322+
},
1323+
_parsedUrl: {
1324+
pathname: '/'
1325+
}
1326+
})
1327+
const res_03 = httpMocks.createResponse()
1328+
1329+
const appconfig = {
1330+
headers: {
1331+
'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS, POST',
1332+
'Access-Control-Allow-Headers': 'Authorization, Content-Type, Origin',
1333+
'Access-Control-Allow-Origin': 'http://boris.com, http://localhost:8080',
1334+
'Access-Control-Max-Age': '1296000'
1335+
},
1336+
params: {
1337+
propName: 'myOwnWhatever'
1338+
}
1339+
}
1340+
1341+
app.reset()
1342+
app.use(appconfig)
1343+
app.all('/Users/:username', (req, res) => res.status(200).send(`Hello ${req.myOwnWhatever.username}${req.myOwnWhatever.lastname ? ` ${req.myOwnWhatever.lastname}` : ''}`))
1344+
const result_01 = app.handleEvent()(req_01, res_01).then(() => {
1345+
assert.equal(res_01._getData(),'Hello nicolas')
1346+
const headers = res_01._getHeaders()
1347+
assert.isOk(headers)
1348+
assert.equal(headers['Access-Control-Allow-Methods'], 'GET, HEAD, OPTIONS, POST')
1349+
assert.equal(headers['Access-Control-Allow-Headers'], 'Authorization, Content-Type, Origin')
1350+
assert.equal(headers['Access-Control-Allow-Origin'], 'http://boris.com, http://localhost:8080')
1351+
assert.equal(headers['Access-Control-Max-Age'], '1296000')
1352+
})
1353+
const result_02 = app.handleEvent()(req_02, res_02).then(() => {
1354+
assert.equal(res_02._getData(),'Hello nicolas dao')
1355+
const headers = res_02._getHeaders()
1356+
assert.isOk(headers)
1357+
assert.equal(headers['Access-Control-Allow-Methods'], 'GET, HEAD, OPTIONS, POST')
1358+
assert.equal(headers['Access-Control-Allow-Headers'], 'Authorization, Content-Type, Origin')
1359+
assert.equal(headers['Access-Control-Allow-Origin'], 'http://boris.com, http://localhost:8080')
1360+
assert.equal(headers['Access-Control-Max-Age'], '1296000')
1361+
})
1362+
const result_03 = app.handleEvent()(req_03, res_03).then(() => {
1363+
assert.equal(res_03.statusCode, 404)
1364+
assert.equal(res_03._getData(), 'Endpoint \'/\' for method GET not found.')
1365+
})
1366+
1367+
return Promise.all([result_01, result_02, result_03])
1368+
})))

0 commit comments

Comments
 (0)