모듈 설치

npm i express
npm i @types/express

 

# src/middleware/guard.ts
import {NextFunction, Request, Response} from "express";

export default (req: Request, res: Response, next: NextFunction) => {
    try {
        ...
        
        req.session = {
            LOGIN_ID: decodeTokenJson.LOGIN_ID
        }
        next();
    } catch (e: unknown) {
        next(e);
    }
}

JWT 검증에 성공한다면,  Request 정보에 LOGIN_IN 속성을 추가하여 뒷 단에서 decode한 값들은 사용하려 한다

 

# src/types/express/index.d.ts
import * as express from "express"

declare global {
  namespace Express {
    interface Request {
      session: {
        LOGIN_ID: string;
      }
    }
  }
}

types/express/index.d.ts 파일을 생성하여, 원하는 속성 타입을 추가한다

 

# tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",          /* JavaScript 버전 */
    "module": "commonjs",        /* 모듈 시스템 */
    "outDir": "./dist",          /* 컴파일된 파일 출력 디렉토리 */
    "rootDir": "./src",          /* 소스 파일 디렉토리 */
    "strict": true,              /* 엄격한 타입 검사 */
    "esModuleInterop": true,     /* ES 모듈과의 상호 운용성 */
    "skipLibCheck": true,         /* 라이브러리 체크 건너뛰기 */
    "typeRoots": ["./src/types", "./node_modules/@types"]
  }
}

typeRoots 속성을 추가한다. 중요한 것은  node_modules/@types 의 값이 나중에 선언되어야 적용된다

'JavaScript > TypeScript' 카테고리의 다른 글

[TS] mysql2 패키지 모듈화  (0) 2024.06.17

+ Recent posts