typescript-rest icon indicating copy to clipboard operation
typescript-rest copied to clipboard

Inject custom Express request properties using @ContextRequestProperty decorator

Open carterhaugh opened this issue 6 years ago • 3 comments
trafficstars

Allows the following behavior:

const authMiddleware = async (req, res, next) => {
  const userId: string = await authenticateRequestAndReturnCurrentUserId(...);
  req.userId = userId;
  next();
}

...

@ Path('people')
class PeopleService {
  @ GET
  getCurrentUser(@ ContextRequestProperty('userId') userId: string) {
}

carterhaugh avatar Jul 19 '19 20:07 carterhaugh

Codecov Report

Merging #105 into master will decrease coverage by 0.05%. The diff coverage is 100.00%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #105      +/-   ##
==========================================
- Coverage   94.46%   94.41%   -0.06%     
==========================================
  Files          14       14              
  Lines        1103     1110       +7     
  Branches      189      189              
==========================================
+ Hits         1042     1048       +6     
- Misses         61       62       +1     
Impacted Files Coverage Δ
src/decorators/parameters.ts 100.00% <100.00%> (ø)
src/server/model/metadata.ts 100.00% <100.00%> (ø)
src/server/parameter-processor.ts 93.44% <100.00%> (+0.10%) :arrow_up:
src/server/server.ts 92.62% <0.00%> (-0.66%) :arrow_down:

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update edcc653...3e941bd. Read the comment docs.

codecov[bot] avatar Jul 19 '19 20:07 codecov[bot]

I don't get it. What is a "custom Express request property" ?

Evanlec avatar Jul 29 '19 17:07 Evanlec

A common pattern in express is to attach custom data to the request prototype from inside a middleware function so that subsequent middlewares/route handlers may have access to it. For example, if you want to restrict access to a route only for authenticated users, you can use a middleware for this purpose, and you can also pass along the user id retrieved from the authentication procedure to the route handler method to save an additional db lookup.

You could then access this value by injecting the req object into your route handler function and then retrieving the new property you attached. This PR makes it so that you can inject the custom property directly into your method, i.e. if you attach a value req.someVal = ...; in your middleware, you can do @ContextRequestProperty('someVal') someVal: type to get access to it in your route handler.

See:

https://stackoverflow.com/questions/12518132/modifying-express-js-request-object

https://stackoverflow.com/questions/37377731/extend-express-request-object-using-typescript

carterhaugh avatar Jul 29 '19 17:07 carterhaugh