typescript-rest
typescript-rest copied to clipboard
Inject custom Express request properties using @ContextRequestProperty decorator
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) {
}
Codecov Report
Merging #105 into master will decrease coverage by
0.05%. The diff coverage is100.00%.
@@ 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 dataPowered by Codecov. Last update edcc653...3e941bd. Read the comment docs.
I don't get it. What is a "custom Express request property" ?
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