Skip to content

Commit

Permalink
feat(decorator): add support for graphql in user roles decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
tupe12334 committed Dec 8, 2021
1 parent d6e004b commit 4b8ffe7
Show file tree
Hide file tree
Showing 6 changed files with 16,121 additions and 6,422 deletions.
29 changes: 26 additions & 3 deletions lib/decorators/user-roles.decorators.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const common_1 = require("@nestjs/common");
const graphql_1 = require("@nestjs/graphql");
function userFactory(ctx) {
const contextType = ctx.getType();
if (contextType === 'http') {
// do something that is only important in the context of regular HTTP requests (REST)
const { user } = ctx.switchToHttp().getRequest();
return user;
}
else if (contextType === 'rpc') {
// do something that is only important in the context of Microservice requests
throw new Error('Rpc context is not implemented yet');
}
else if (contextType === 'ws') {
// do something that is only important in the context of Websockets requests
throw new Error('Websockets context is not implemented yet');
}
else if (ctx.getType() === 'graphql') {
// do something that is only important in the context of GraphQL requests
const gqlExecutionContext = graphql_1.GqlExecutionContext.create(ctx);
return gqlExecutionContext.getContext().req.user;
}
throw new Error('Invalid context');
}
/**
* Access the user roles from the request object i.e `req.user.roles`.
*
* You can pass an optional property key to the decorator to get it from the user object
* e.g `@UserRoles('premissions')` will return the `req.user.premissions` instead.
* e.g `@UserRoles('permissions')` will return the `req.user.permissions` instead.
*/
exports.UserRoles = common_1.createParamDecorator((data, ctx) => {
const request = ctx.switchToHttp().getRequest();
return data ? request.user[data] : request.user.roles;
const user = userFactory(ctx);
return data ? user[data] : user.roles;
});
9 changes: 5 additions & 4 deletions lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,17 @@
"nestjs",
"access",
"roles",
"premissions",
"permissions",
"nestjs modules",
"addons"
],
"author": "Shady Khalifa <shekohex@gmail.com>",
"license": "MIT",
"devDependencies": {
"@nestjs/common": "^6.0.1",
"@nestjs/core": "^6.0.1",
"@nestjs/testing": "^6.1.1",
"@nestjs/common": "^7.6.18",
"@nestjs/core": "^7.6.18",
"@nestjs/graphql": "^7.9.1",
"@nestjs/testing": "^7.6.18",
"@types/jest": "^24.0.12",
"@types/node": "^10.1.2",
"coveralls": "^3.0.1",
Expand Down
Loading

0 comments on commit 4b8ffe7

Please sign in to comment.