Typescript를 사용하여 Express Request 객체 확장
typescript를 사용하여 미들웨어에서 요청 개체를 표현하는 속성을 추가합니다. 그러나 추가 속성을 추가하는 방법을 알 수 없습니다. 가능하면 대괄호 표기법을 사용하지 않는 것이 좋습니다.
가능한 경우 이와 유사한 것을 찾고 있습니다.
app.use((req, res, next) => {
req.property = setProperty();
next();
});
사용자 정의를 정의하고 선언 병합 이라는 Typescript의 기능을 사용합니다 . 이것은 일반적으로 사용 됩니다.method-override
파일 custom.d.ts
을 만들고 tsconfig.json
의 files
섹션 에 포함해야합니다 . 내용은 다음과 같이 보일 수 있습니다.
declare namespace Express {
export interface Request {
tenant?: string
}
}
이렇게하면 코드의 어느 시점에서든 다음과 같은 것을 사용할 수 있습니다.
router.use((req, res, next) => {
req.tenant = 'tenant-X'
next()
})
router.get('/whichTenant', (req, res) => {
res.status(200).send('This is your tenant: '+req.tenant)
})
의 주석 에서index.d.ts
제안한대로 Express
새 멤버를 전역 네임 스페이스에 선언하기 만하면 됩니다. 예 :
declare global {
namespace Express {
interface Request {
context: Context
}
}
}
전체 예 :
import * as express from 'express';
export class Context {
constructor(public someContextVariable) {
}
log(message: string) {
console.log(this.someContextVariable, { message });
}
}
declare global {
namespace Express {
interface Request {
context: Context
}
}
}
const app = express();
app.use((req, res, next) => {
req.context = new Context(req.url);
next();
});
app.use((req, res, next) => {
req.context.log('about to return')
res.send('hello world world');
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
전역 네임 스페이스 확장 은 내 GitBook에서 자세히 다룹 니다 .
받아 들인 대답 (다른 사람과 대답)은 나를 위해 작동하지 않지만
declare module 'express' {
interface Request {
myProperty: string;
}
}
했다. 누군가를 도울 수 있기를 바랍니다.
최신 버전의 Express의 경우 express-serve-static-core
모듈 을 보강해야 합니다.
이제 Express 수업가 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8fb0e959c2c7529b5fa4793a44b41b797ae671b9/types/express/index.d.ts#L19 에서 제공되기 때문에 필요합니다.
기본적으로 다음을 사용하십시오.
declare module 'express-serve-static-core' {
interface Request {
myField?: string
}
interface Response {
myField?: string
}
}
어떤 것도 나를 위해 일하지 솔루션 중 어느 것도 나를 위해. 요청 인터페이스를 확장했습니다.
import {Request} from 'express';
export interface RequestCustom extends Request
{
property: string;
}
그런 다음 사용하려는 비용 :
import {NextFunction, Response} from 'express';
import {RequestCustom} from 'RequestCustom';
someMiddleware(req: RequestCustom, res: Response, next: NextFunction): void
{
req.property = '';
}
편집 : 최근 버전의 TypeScript가 이에 대해 불평합니다. 대신 다음을 수행해야했습니다.
someMiddleware(expressRequest: Request, res: Response, next: NextFunction): void
{
const req = expressRequest as RequestCustom;
req.property = '';
}
TypeScript에서 인터페이스는 개방형입니다. 즉, 재정의하기 만하면 어디서나 속성을 추가 할 수 있습니다.
이 express.d.ts 파일을 사용하고 있다는 점을 고려 하면 요청 인터페이스를 재정 의하여 추가 필드를 추가 할 수 있습니다.
interface Request {
property: string;
}
그런 다음 미들웨어 함수에서 req 매개 변수 에도이 속성이 있어야합니다. 코드를 변경하지 않고 사용할 수 있어야합니다.
한 가지 가능한 해결책은 "모든 대상에 이중 캐스팅"을 사용하는 것입니다.
1- 속성으로 인터페이스 정의
export interface MyRequest extends http.IncomingMessage {
myProperty: string
}
2- 이중 캐스트
app.use((req: http.IncomingMessage, res: http.ServerResponse, next: (err?: Error) => void) => {
const myReq: MyRequest = req as any as MyRequest
myReq.myProperty = setProperty()
next()
})
이중 주조의 장점은 다음과 같습니다.
- 타이핑이 가능합니다
- 기존 정의를 오염시키지 않고 확장하여 혼란을 피합니다.
- 캐스팅이 명시 적이므로
-noImplicitany
플래그로 벌금을 컴파일합니다.
또는 빠른 (입력되지 않은) 경로가 있습니다.
req['myProperty'] = setProperty()
(자신의 속성으로 기존 정의 파일을 편집하지 마십시오. 유지 관리 할 수 없습니다. 정의가 잘못된 경우 풀 요청을 엽니 다.)
편집하다
이 경우 간단한 캐스팅이 작동합니다. req as MyRequest
이것은 매우 오래된 질문이지만 최근 에이 문제를 우연히 발견했습니다. 허용 된 답변은 정상적으로 작동하지만 사용자 정의 인터페이스를 추가해야했습니다 Request
-내 코드에서 사용했던 인터페이스는 허용 된 인터페이스와 잘 작동하지 않았습니다. 대답. 논리적으로 나는 이것을 시도했다.
import ITenant from "../interfaces/ITenant";
declare namespace Express {
export interface Request {
tenant?: ITenant;
}
}
그러나 Typescript는 .d.ts
파일을 전역 가져 오기로 처리하고 가져 오기가 있으면 일반 모듈로 처리 되기 때문에 작동하지 않았습니다 . 이것이 위의 코드가 표준 타이프 스크립트 설정에서 작동하지 않는 이유입니다.
내가 한 일은 다음과 같습니다.
// typings/common.d.ts
declare namespace Express {
export interface Request {
tenant?: import("../interfaces/ITenant").default;
}
}
// interfaces/ITenant.ts
export interface ITenant {
...
}
이 문제에 대한 답변이 있었을 수도 있지만 조금만 공유하고 싶습니다. 이제 다른 답변과 같은 인터페이스가 너무 제한적일 수 있지만 실제로 필요한 속성을 유지 한 다음 추가 할 속성을 추가 할 수 있습니다. 유형이 string
값 유형 인 키any
import { Request, Response, NextFunction } from 'express'
interface IRequest extends Request {
[key: string]: any
}
app.use( (req: IRequest, res: Response, next: NextFunction) => {
req.property = setProperty();
next();
});
이제이 객체에 원하는 추가 속성을 추가 할 수도 있습니다.
참고 URL : https://stackoverflow.com/questions/37377731/extend-express-request-object-using-typescript
'ProgramingTip' 카테고리의 다른 글
왜 빈 사전이 컴파일러에서 위험한입니까? (0) | 2020.10.28 |
---|---|
Python Pandas에서 두 값 사이의 DataFrame에서 행을 선택하는 방법은 무엇입니까? (0) | 2020.10.28 |
jQuery가 다른 Javascript 프레임 워크에 비해 채택되는 이유는 무엇입니까? (0) | 2020.10.28 |
바이트 배열을 맵 키로 사용 (0) | 2020.10.28 |
선택을 반복하고 선택하거나 선택하지 않는 각을 계산합니다. (0) | 2020.10.28 |