gpt4 book ai didi

typescript - 在我的 Controller 中使用模型中定义的实例方法

转载 作者:行者123 更新时间:2023-12-03 22:37:52 24 4
gpt4 key购买 nike

我在尝试使用 Sequelize 和 Typescript 时遇到以下错误,这两个我都很陌生:

(node:17276) UnhandledPromiseRejectionWarning: TypeError: week.calculateDays is not a function    

我的 Controller 中有以下内容供我的路线使用:
import { Request, Response } from "express";
import models from "../models";

export class Weeks {
public static calculateDays = async (req: Request, res: Response) => {
console.log(req.params);
await models.Week.findByPk(req.params.id).then(week => {
if (week) {
console.log("Week found:", week);
week.calculateDays();
}
});
};
}

并在模型中定义了以下内容:
import Sequelize from "sequelize";
import { SequelizeAttributes } from "../typings/SequelizeAttributes";
import { WeekAttributes } from "../interfaces/attributes";
import { WeekInstance } from "../interfaces/instances";
import models from "../models";
import { SessionAttributes } from "./sessions";

export const WeekFactory = (
sequelize: Sequelize.Sequelize,
DataTypes: Sequelize.DataTypes
): Sequelize.Model<WeekInstance, WeekAttributes> => {
const attributes: SequelizeAttributes<WeekAttributes> = {
....attributes of the model....
};

const Week = sequelize.define<WeekInstance, WeekAttributes>(
"weeks",
attributes,
{
instanceMethods: {
calculateDays: async function (this: WeekInstance) {
console.log("Inside class method calculateDays");
return await calculateDays(this.id!);
}
}
}
);

const calculateDays = async (weekId: number) => {
.......
}
return Week;
};

我真的很感激任何一种方向,因为我不确定我在这里错过了什么。

最佳答案

我相信问题在于您声明 calculateDays 方法的方式。这不应接收 WeekInstance 参数,您可以在函数内部正常使用 this。另外,我建议不要对 out 函数 calculateDays 使用相同的名称。我相信它无法从实例方法内部访问并且有点困惑,所以我将它重命名为 calculateDaysForWeek

instanceMethods: {
calculateDays: async function () {
console.log("Inside class method calculateDays");
return await calculateDaysForWeek(this.id!);
}
}

关于如何创建实例方法的好引用: https://github.com/sequelize/sequelize/issues/9760

关于typescript - 在我的 Controller 中使用模型中定义的实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55922563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com