我试图将 cookie-parser - https://www.npmjs.com/package/cookie-parser添加到我的 NestJS 应用程序:
import * as cookieParser from 'cookie-parser';
consumer
.apply(cookieParser())
.forRoutes('/');
Run Code Online (Sandbox Code Playgroud)
当正常运行(编译并运行 js)时,不会发生错误并且代码按预期工作,但是当尝试在相同的代码上运行 e2e 测试(使用 Jest、Supertest)时,在启动过程中会发生以下错误:
TypeError: cookieParser is not a function
此外,当使用cookieParser代替时cookieParser(),不会发生上述错误,但代码无法按预期工作。
在 e2e 测试期间,我使用了Test.createTestingModule然后moduleFixture.createNestApplication().
你知道这里有什么问题吗?谢谢你。
我开发了一个嵌套的 JS 模块。我使用 npm publish 在 npm 上发布了它。
现在我想在基于 nodejs 和 express 的项目中使用该 NestJS 模块。
请告知我是否可以在 node/express 项目中使用 nestjs 模块。如果是,是否有任何可用的文档。
根据用户的评论添加更多细节。
这是一种库,它有一个模块,导出的方法很少。这些方法包含调用 aws sns 服务以发送推送通知的实现。
我现在找到了一个尝试使用它的链接。
https://codeburst.io/https-chidume-nnamdi-com-npm-module-in-typescript-12b3b22f0724
提前致谢。
我正在使用 nestjs 库上传文件,但这些文件没有文件扩展名
@Post('upload')
@UseInterceptors(
FilesInterceptor('files', 6, {
dest: 'images',
fileFilter: (req, file, cb) => {
file.filename = Date.now() + '-' +file.originalname ;
cb(null, true);
},
})
)
uploadFile(
@UploadedFiles() files
){
console.log(files);
}Run Code Online (Sandbox Code Playgroud)
尝试为我的 nestjs 应用程序编写测试脚本。
我有控制器/服务框架,看起来像这样:
控制器:
export class MyController {
constructor(
protected _svc: MyService
) {}
@Get()
async getAll(): Promise<Array<Person>> {
return await this._svc.findAll();
}
}
Run Code Online (Sandbox Code Playgroud)
服务:
@Injectable()
export class MyService extends DbService < Person > {
constructor(
private _cache: CacheService
) {
super(...);
}
async findAll() {
return super.findAll().then(res => {
res.map(s => {
this._cache.setValue(`key${s.ref}`, s);
});
return res;
});
}
Run Code Online (Sandbox Code Playgroud)
基类:
@Injectable()
export abstract class DbService<T> {
constructor() {}
async findAll(): Promise<Array<T>> {
...
}
}
Run Code Online (Sandbox Code Playgroud)
我的控制器是在 API 上调用端点时的入口点。这调用了扩展 …
我在nestjs项目的tsconfig.json中配置了路径别名,但是运行时出现错误。
我尝试像Angular一样配置,但是nestjs出现错误
这是我的 tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"paths": {
"~auth/*": ["src/auth/*"]
}
},
"exclude": ["node_modules"]
}
Run Code Online (Sandbox Code Playgroud)
像这样使用它
import { userLoginJwt } from '~auth/jwt-names'
Run Code Online (Sandbox Code Playgroud)
启动错误
$ npm run start:dev
[0] internal/modules/cjs/loader.js:584
[0] throw err;
[0] ^
[0]
[0] Error: Cannot find module 'src/auth/jwt-names'
Run Code Online (Sandbox Code Playgroud)
抱歉,我在此强调,跑步npm run start是没问题的,但是跑步npm run start:dev会导致意想不到的情况。
据我所知,要使令牌无效,这是存储令牌的最佳方法,它是数据库的到期日期时间。要验证它,您只需从数据库中选择它,如果它存在,就知道它已失效。此外,您可以在数据库的过期日期时间之前删除每个过期的令牌。
因此,我创建了一个中间件,该中间件从授权标头中提取令牌,并将该令牌和到期日期时间附加到该request对象。signOut路由使令牌失效需要日期时间。
async use(req: any, res: Response, next: NextFunction) {
try {
const headers: IncomingHttpHeaders = req.headers;
const authorization: string = headers.authorization;
const bearerToken: string[] = authorization.split(' ');
const token: string = bearerToken[1];
if (await this.authenticationsRepository.findByEncodedToken(token)) { // invalidated token?
throw new Error(); // jump to catch
}
req.tokenPayload = verifyToken(token); // calls jwt.verify with secret
next();
} catch (error) {
throw new UnauthorizedException();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如何exp从令牌中提取属性以计算到期日期时间呢?
我有一个使用nestjs和的应用程序MiddlewareConsumer。我想知道是否有办法根据标头值跳过中间件?
我检查了文档,发现我只能使用路径或方法(就像我现在所做的那样),但也许我遗漏了什么?
我的代码示例:
export class AuthorizationModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(DiscriminatorValidator).with(common.USERS).forRoutes(
{path: RELATIVE_RESOURCE_PATH, method: RequestMethod.POST},{path: RELATIVE_RESOURCE_PATH, method: RequestMethod.PUT});
consumer.apply(validate).forRoutes(AuthorizationController);
consumer.apply(HeadersValidator).with().forRoutes(AuthorizationController);
consumer.apply(ContextAndHeadersMiddleware).forRoutes(AuthorizationController);
}
}
Run Code Online (Sandbox Code Playgroud) 我的 REST API 中有一个查询参数,其值应受枚举类型的限制。当客户端给出不同的东西时,我正在寻找一种抛出“错误请求”错误的方法。
我的枚举看起来像这样:
export enum Precision {
S = 's',
MS = 'ms',
U = 'u',
NS = 'ns',
}
Run Code Online (Sandbox Code Playgroud)
我的控制器功能如下所示:
@Get(':deviceId/:datapoint/last')
@ApiOkResponse()
@ApiQuery({name: 'precision', enum: Precision})
getLastMeasurement(
@Param('deviceId') deviceId: string,
@Param('datapoint') datapoint: string,
@Query('precision') precision: Precision = Precision.S,
@Res() response: Response,
) {
console.log(precision);
....
response.status(HttpStatus.OK).send(body);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是该函数也接受其他值(例如,我可以发送 f 作为查询参数的值)。该函数不会向客户端返回错误,但我不想在每个控制器函数的开头编写 if else 块。
我想对此有一个相当简单的解决方案,但是当我尝试在互联网上查找它时,我总是在 DTO 中获得类验证的结果,而不是直接在查询参数/REST 控制器中进行简单的枚举验证。
谢谢你的时间,
J
我正在使用带有 TypeORM 的 NestJS
我得到了两个具有关系的实体:
export class Device {
@PrimaryGeneratedColumn()
id: number;
@Column("macaddr")
mac: string;
@OneToMany(type => DeviceStatus, deviceStatus => deviceStatus.mac)
@JoinColumn()
status: DeviceStatus[]
@Column()
created: Date;
}
export class DeviceStatus {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(type => Device, device => device.mac)
@JoinColumn({ name: "mac", referencedColumnName: "mac" })
mac: Device;
@Column()
deviceState: number;
@Column()
created: Date;
}
Run Code Online (Sandbox Code Playgroud)
我想获取 Device 但只有它的status属性是最新的 DeviceStatus 。
现在我这样做:
const deviceQuery: Device = await this.deviceRepository
.createQueryBuilder("device")
.where('device.id = :id AND "device"."userId" = :user', {id: id, …Run Code Online (Sandbox Code Playgroud) 我正在尝试为我的 GraphQL 端点创建和 e2e 测试。在努力让 Jest 找到测试之后,我现在看到 Jest 尝试将测试作为 JavaScript 运行,而不是 TypeScript。这是一个错误输出:
SyntaxError: /server/__tests__/users.e2e-spec.ts: Unexpected token, expected ";" (9:10)
7 |
8 | describe('AppController (e2e)', () => {
> 9 | let app: INestApplication
| ^
10 | let apolloClient: ApolloServerTestClient
11 |
12 | beforeEach(async () => {
at Parser.raise (node_modules/@babel/parser/src/parser/location.js:41:63)
at Parser.unexpected (node_modules/@babel/parser/src/parser/util.js:150:16)
at Parser.semicolon (node_modules/@babel/parser/src/parser/util.js:123:40)
at Parser.parseVarStatement (node_modules/@babel/parser/src/parser/statement.js:703:10)
at Parser.parseStatementContent (node_modules/@babel/parser/src/parser/statement.js:216:21)
at Parser.parseStatement (node_modules/@babel/parser/src/parser/statement.js:146:17)
at Parser.parseBlockOrModuleBlockBody (node_modules/@babel/parser/src/parser/statement.js:865:25)
at Parser.parseBlockBody (node_modules/@babel/parser/src/parser/statement.js:841:10)
at Parser.parseBlock (node_modules/@babel/parser/src/parser/statement.js:818:10)
at Parser.parseFunctionBody (node_modules/@babel/parser/src/parser/expression.js:1964:24)
Run Code Online (Sandbox Code Playgroud)
这是 …
nestjs ×10
node.js ×5
typescript ×5
jestjs ×3
javascript ×2
express ×1
jwt ×1
rest ×1
typeorm ×1