Serverless+fastify+TypeORM部署报getParameters属性未定义错误
你遇到的Cannot read property 'getParameters' of undefined错误本质来自两个核心问题:
- Serverless 冷启动无状态特性导致TypeORM默认连接丢失,你直接调用
getConnection()时没有可用的已初始化连接 - 实体类装饰器元数据未被正确加载,或者TypeORM初始化时未正确识别实体配置
1. 新增TypeORM连接容错初始化逻辑
不要直接调用全局getConnection(),新增连接缓存逻辑,冷启动时自动初始化连接,同时必须显式引入实体类,不要用glob路径匹配实体(Serverless打包时glob路径会失效,匹配不到实体文件):
// src/db/connection.ts import "reflect-metadata"; import { createConnection, Connection } from "typeorm"; import { Finca } from "./entities/Finca"; // 其他实体类也在这里引入 let cachedConnection: Connection | null = null; export const getDbConnection = async () => { if (cachedConnection?.isConnected) { return cachedConnection; } // 数据库配置换成你自己的参数,建议从环境变量读取 cachedConnection = await createConnection({ type: "mysql", host: process.env.DB_HOST, port: Number(process.env.DB_PORT || 3306), username: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, entities: [Finca], // 所有用到的实体都显式放到数组里 synchronize: false, logging: false, }); return cachedConnection; };
2. 改造业务接口代码
把原来直接调用getConnection()的逻辑换成上面的容错方法:
import { getDbConnection } from "../db/connection"; import { Finca } from "../db/entities/Finca"; export const getFincas = async (_req: any, reply: any) => { const connection = await getDbConnection(); const fincas = await connection .createQueryBuilder() .select("finca") .from(Finca, "finca") .getMany(); reply.send(fincas); };
3. 调整项目配置
- 把
reflect-metadata的导入放到整个项目入口(server.ts)的第一行,确保装饰器元数据优先加载 - 调整
tsconfig.json配置,适配Node.js运行环境,同时把实体类路径加入编译范围:
{ "compilerOptions": { "strict": false, "strictNullChecks": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "esModuleInterop": true, "target": "es2020", // 从es5调整为es2020,匹配Serverless Node.js运行环境 "module": "commonjs", "lib": ["ES2020"], "moduleResolution": "node", "removeComments": true, "forceConsistentCasingInFileNames": true }, "include": [ "server.ts", "api/**/*.ts", "db/**/*.ts" // 新增实体类所在路径,确保被编译 ] }
4. 检查Serverless打包配置
确保你的Serverless打包插件(比如serverless-plugin-typescript、esbuild)没有排除TypeORM依赖和实体类文件,不要开启过度的tree shaking配置,避免元数据被误删。
内容的提问来源于stack exchange,提问作者sebastianlion12
相关产品推荐
相关产品推荐

