【发布时间】:2020-12-12 23:29:52
【问题描述】:
我的 NestJS 控制器收到以下 JSON 响应:
{
"data": [{ ... users ... }]
}
为了实现这个“包络”的东西,我使用了拦截器:
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import { plainToClass } from 'class-transformer'
import { ResponseObjectInterface } from './response-object.interface'
interface ClassType<T> {
new (): T
}
@Injectable()
export class TransformInterceptor<T>
implements NestInterceptor<Partial<T>, ResponseObjectInterface<T> | T> {
constructor(
private readonly classType: ClassType<T>,
private readonly envelope = true
) {}
intercept(
context: ExecutionContext,
next: CallHandler
): Observable<ResponseObjectInterface<T> | T> {
return next
.handle()
.pipe(
map(data =>
this.envelope
? { data: plainToClass(this.classType, data) }
: plainToClass(this.classType, data)
)
)
}
}
它按预期工作。 现在我必须更改它并在响应中添加另一个根属性。这个:
{
"data": { ... user ... },
"_signed": "jwt" --> String or NULL
}
我还有其他对象(产品、订阅...等)。它们都具有相同的 JSON 签名。但他们将在_signed 中有NULL。它将是空的。只有用户签名。
我认为拦截器中有一些逻辑可以添加属性,但我不知道该怎么做。实现此功能的最佳方式是什么?
【问题讨论】:
-
你的疑惑是如何获取jwt?如果是这样,您从执行上下文访问请求,例如 context.switchToHttp().req.headers.authorization
-
没有。我创建了 jwt。我的问题只是关于有效载荷的构造。