createQueryRunner는 undefined속성을 읽을 수 없다
const qr = this.dataSource.createQueryRunner();ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'createQueryRunner')
TypeError: Cannot read properties of undefined (reading 'createQueryRunner')
at TransactionInterceptor.intercept (C:\Users\Administrator\Desktop\cf_sns\src\common\interceptor\transaction.interceptor.ts:21:32)
이 에러가 떠서 postman으로 테스트를 진행하지 못하고있습니다.
dataSource도 typeorm에서 import 해서 사용했는데 컨트롤러에서 트랜잭션을 사용할때는 됐다가 인터셉터로 따로 빼서 사용하려고할 때 발생한 오류입니다.
답변 1
0
안녕하세요!
에러를 번역해보면 createQueryRunner를 undefined에 실행하려고하니 나는 에러네요.
즉, datasource가 undefined입니다.
정상적인 상황이라면 datasource가 undefined가 될 수 없습니다.
this.datasource가 왜 null인지 확인을 하셔야 할 것 같습니다.
interceptor로 따로 빼서 실행하려 할때 나는 에러라면 어떤 코드 변경이 있었는지, 실수한건 없는지 확인 해보셔야겠습니다.
도저히 모르겠다면 문제라고 생각되는 부분들을 더 넓게 캡쳐를 해주셔야합니다. 감사합니다!
감사합니다!
0
// posts.controller.ts
import {
Body,
Controller,
Post,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { QueryRunner as QR } from 'typeorm';
import { TransactionInterceptor } from 'src/common/interceptor/transaction.interceptor';
import { QueryRunner } from 'src/common/decorator/query-runner.decorator';
@Post()
@UseGuards(AccessTokenGuard)
@UseInterceptors(TransactionInterceptor)
async postPosts(
@User('id') userId: number,
@Body() body: CreatePostDto,
@QueryRunner() qr: QR,
) {
const post = await this.postsService.createPost(userId, body, qr);
// throw new InternalServerErrorException('TEST');
for (let i = 0; i < body.images.length; i++) {
await this.postsImagesService.createPostImage(
{
post,
order: i,
path: body.images[i],
type: ImageModelType.POST_IMAGE,
},
qr,
);
}
return this.postsService.getPostById(post.id, qr);
}// transaction.interceptor.ts
/* eslint-disable prettier/prettier */
import {
CallHandler,
ExecutionContext,
InternalServerErrorException,
NestInterceptor,
} from '@nestjs/common';
import { Observable, catchError, tap } from 'rxjs';
import { DataSource } from 'typeorm';
export class TransactionInterceptor implements NestInterceptor {
constructor(private readonly dataSource: DataSource) {}
async intercept(
context: ExecutionContext,
next: CallHandler<any>,
): Promise<Observable<any>> {
const req = context.switchToHttp().getRequest();
// 트랜잭션과 관련된 모든 쿼리를 담당할
// 쿼리 러너를 생성한다.
const qr = this.dataSource.createQueryRunner();
// 쿼리 러너에 연결한다.
await qr.connect();
// 쿼리 러너에서 트랜잭션을 시작한다.
// 이 시점부터 같은 쿼리러너를 사용하면
// 트랜잭션 안에서 데이터베이스 액션을 실행할 수 있다.
await qr.startTransaction();
req.queryRunner = qr;
return next.handle().pipe(
catchError(async (e) => {
await qr.rollbackTransaction();
await qr.release();
throw new InternalServerErrorException(e.message);
}),
tap(async () => {
await qr.commitTransaction();
await qr.release();
}),
);
}
}
해당 강의에서 사용된 코드 부분입니다.
cascade 질문
0
49
1
@types/bcrypt 설치과정이 누락된것같습니다.
0
60
1
process.env port key 에러
0
55
1
추상화
0
56
1
[공유] DTO optional 필드가 undefined로 잡혀 TypeORM 조건이 깨지는 현상
0
114
2
where 키워드가 들어가는 메서드와 아닌 메서드
0
59
1
BearerTokenGuard에서 db를 조회해서 유저 정보를 불러오는 이유?
0
75
1
app.controller app.service 는 지워도되나요?
0
75
1
@JoinColumn을 쓰는 경우와 안쓰는 경우의 차이
0
86
1
포트 3000에서 listen하는 곳까지 넘어가지 않습니다.
0
76
1
PickType 사용 시 `as const`를 꼭 사용해야 하나요?
0
112
2
socket connect 오류
0
111
2
강의를 들으면서 궁금한 점
0
104
2
DELETE 요청의 반환값은 어떤 기준으로 결정하는 게 좋을까요?
0
72
2
커리큘럼 질문
0
103
2
put 요청은 언제
0
98
3
typeorm VS prisma
0
357
2
142 강의 > 4:00 > 포스트멘 활용 관련 질문 드립니다.
0
81
2
User 데코레이터 버그 수정 전달드립니다.
0
70
1
git 주소 부탁드립니다.
0
118
2
nest g resource 명령어 에러
0
102
2
로그인 엔드포인트 관련 질문
0
89
2
yarn으로 express 다운 후 node 2_server.js 실행 안되는 경우
0
153
3
"흔히 사용되는 메서드" 강의 관련 질문입니다~
0
98
2





