-
Notifications
You must be signed in to change notification settings - Fork 2
feat: implement guard support (#24) #80
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
"@unioc/adapter-nestjs": patch | ||
--- | ||
|
||
feat: implement guard support (#24) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
22 changes: 22 additions & 0 deletions
22
packages/adapter/adapter-nestjs/src/execution-context-builder.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import type { ContextType, ExecutionContext, Type } from '@nestjs/common' | ||
import type { IClass } from '@unioc/shared' | ||
import { ArgumentsHostBuilder } from './arguments-host-builder' | ||
|
||
export class ExecutionContextBuilder extends ArgumentsHostBuilder implements ExecutionContext { | ||
constructor( | ||
protected readonly _args: readonly unknown[], | ||
protected readonly _type: ContextType, | ||
protected readonly _target: IClass, | ||
protected readonly _handler: (...args: unknown[]) => unknown, | ||
) { | ||
super(_args, _type) | ||
} | ||
|
||
getClass<T = any>(): Type<T> { | ||
return this._target | ||
} | ||
|
||
getHandler(): (...args: unknown[]) => unknown { | ||
return this._handler | ||
} | ||
} |
72 changes: 72 additions & 0 deletions
72
packages/adapter/adapter-nestjs/src/restful/ending-handler.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
import type { IResult } from '@unioc/shared' | ||
import type { IRestfulConnect } from '@unioc/web' | ||
|
||
export class EndingHandler { | ||
async sendConnectEndingResponse(ctx: IRestfulConnect.WebContext, result: IResult): Promise<void> { | ||
if (ctx.response.writableEnded || ctx.response.writableFinished) | ||
return | ||
|
||
if ('send' in ctx.response && typeof ctx.response.send === 'function' && 'status' in ctx.response && typeof ctx.response.status === 'function') { | ||
if (result.type === 'result') { | ||
ctx.response.send(result.value) | ||
} | ||
else { | ||
ctx.response.status(500).send({ | ||
statusCode: 500, | ||
message: 'Internal Server Error', | ||
error: await this._toReadableError(result.error), | ||
}) | ||
} | ||
return | ||
} | ||
|
||
if (result.type === 'result') { | ||
ctx.response.end(await this._toSendableString(result.value)) | ||
} | ||
else { | ||
ctx.response.statusCode = 500 | ||
ctx.response.end( | ||
await this._toSendableString({ | ||
statusCode: 500, | ||
message: 'Internal Server Error', | ||
error: await this._toReadableError(result.error), | ||
}), | ||
) | ||
} | ||
} | ||
|
||
private async _stringifyAsync(data: unknown): Promise<string> { | ||
return JSON.stringify(data) | ||
} | ||
|
||
private async _toSendableString(data: unknown): Promise<string> { | ||
if (typeof data === 'string') | ||
return data | ||
if (typeof data === 'object' && data !== null) { | ||
return await this._stringifyAsync(data) | ||
.catch(async error => this._stringifyAsync({ | ||
statusCode: 500, | ||
message: 'Internal Server Error', | ||
error: await this._toReadableError(error), | ||
})) | ||
.catch(async error => this._stringifyAsync({ | ||
statusCode: 500, | ||
message: 'Internal Server Error', | ||
error: await this._toReadableError(error), | ||
})) | ||
} | ||
return String(data) | ||
} | ||
|
||
private async _toReadableError(error: unknown): Promise<Record<string, unknown>> { | ||
if (error && error instanceof Error) { | ||
const result: Record<string, unknown> = {} | ||
if (error.name !== undefined) | ||
result.name = error.name | ||
for (const key of Reflect.ownKeys(error)) | ||
result[key as string] = error[key as keyof Error] | ||
return result | ||
} | ||
return error as Record<string, unknown> | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -1,4 +1,4 @@ | ||||||||||||||||||||||||||||||
import type { ArgumentMetadata, ArgumentsHost, ExceptionFilter, PipeTransform } from '@nestjs/common' | ||||||||||||||||||||||||||||||
import type { ArgumentMetadata, ArgumentsHost, CanActivate, ExceptionFilter, ExecutionContext, PipeTransform } from '@nestjs/common' | ||||||||||||||||||||||||||||||
import type { IArgument } from '@unioc/core' | ||||||||||||||||||||||||||||||
import type { IClass } from '@unioc/shared' | ||||||||||||||||||||||||||||||
import type { IHttpParam, IRestfulConnect, IRestfulScanner } from '@unioc/web' | ||||||||||||||||||||||||||||||
|
@@ -120,6 +120,16 @@ export class NestJSRestfulScanner extends RestfulScanner implements IRestfulScan | |||||||||||||||||||||||||||||
return 'no-match' | ||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
async executeGuards(resolvedGuards: CanActivate[], context: ExecutionContext): Promise<boolean> { | ||||||||||||||||||||||||||||||
for (const guard of resolvedGuards) { | ||||||||||||||||||||||||||||||
const canActivate = await guard.canActivate(context) | ||||||||||||||||||||||||||||||
if (canActivate === true) | ||||||||||||||||||||||||||||||
continue | ||||||||||||||||||||||||||||||
return false | ||||||||||||||||||||||||||||||
Comment on lines
+125
to
+128
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The guard execution does not include error handling; if guard.canActivate throws an exception, it could lead to unhandled errors. Consider wrapping this call in a try-catch block to provide a controlled failure response.
Suggested change
Copilot uses AI. Check for mistakes. Positive FeedbackNegative Feedback |
||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||
return true | ||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
resolveConnectHandler(): IRestfulConnect.Handler { | ||||||||||||||||||||||||||||||
return new NestJSRestfulHandler() | ||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import { CanActivate, Controller, ExecutionContext, Get, Injectable, UseGuards } from '@nestjs/common' | ||
import { ExpressApp } from '@unioc/web-express' | ||
import request from 'supertest' | ||
import { NestJS } from '../src' | ||
import 'reflect-metadata' | ||
|
||
it('should use guard', async () => { | ||
@Injectable() | ||
class TestGuard implements CanActivate { | ||
canActivate(_context: ExecutionContext): boolean { | ||
return false | ||
} | ||
} | ||
|
||
@Controller() | ||
class TestController { | ||
@Get('/test-guard') | ||
@UseGuards(TestGuard) | ||
test() { | ||
return 'ok' | ||
} | ||
} | ||
|
||
const app = new ExpressApp().use(NestJS, { | ||
controllers: [TestController], | ||
providers: [TestGuard], | ||
}) | ||
await app.initialize() | ||
|
||
await request(app.getExpressApp()) | ||
.get('/test-guard') | ||
.expect(401) | ||
}) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] Chaining two consecutive .catch calls on _stringifyAsync may hide errors rather than handling them explicitly. Consider refactoring this logic with a try-catch block for clearer and more reliable error handling.
Copilot uses AI. Check for mistakes.