diff --git a/.vscode/launch.json b/.vscode/launch.json index 1e356252a..7508afd08 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -11,7 +11,12 @@ "skipFiles": [ "/**" ], - "program": "${workspaceFolder}\\setup\\runner.js", + "runtimeExecutable": "npm", + "args": [ + "run", + "test:sqlite" + ], + // "program": "${workspaceFolder}\\setup\\runner.ts", "env": { "LOCAL_SSCCE": "true", "DIALECT": "sqlite" diff --git a/src/sscce-sequelize-6.ts b/src/sscce-sequelize-6.ts index c90761b96..ce77d9d5d 100644 --- a/src/sscce-sequelize-6.ts +++ b/src/sscce-sequelize-6.ts @@ -1,4 +1,4 @@ -import { DataTypes, Model } from 'sequelize'; +import { BelongsToGetAssociationMixin, DataTypes, ForeignKey, InferAttributes, InferCreationAttributes, Model } from 'sequelize'; import { createSequelize6Instance } from '../setup/create-sequelize-instance'; import { expect } from 'chai'; import sinon from 'sinon'; @@ -21,21 +21,64 @@ export async function run() { }, }); - class Foo extends Model {} + class Foo extends Model, InferCreationAttributes> { + declare id?: string; + declare name: string; + declare BarId: ForeignKey; + declare getBar: BelongsToGetAssociationMixin; + } + class Bar extends Model, InferCreationAttributes> { + declare id?: string; + declare name: string; + } Foo.init({ + id: { + type: DataTypes.INTEGER, + autoIncrement: true, + primaryKey: true + }, name: DataTypes.TEXT, }, { sequelize, modelName: 'Foo', }); + Bar.init({ + id: { + type: DataTypes.INTEGER, + autoIncrement: true, + primaryKey: true + }, + name: DataTypes.TEXT, + }, { + sequelize, + modelName: 'Bar', + }); + + Bar.hasMany(Foo); + Foo.belongsTo(Bar); + // You can use sinon and chai assertions directly in your SSCCE. const spy = sinon.spy(); sequelize.afterBulkSync(() => spy()); await sequelize.sync({ force: true }); expect(spy).to.have.been.called; - console.log(await Foo.create({ name: 'TS foo' })); - expect(await Foo.count()).to.equal(1); + const theBar = await Bar.create({ name: 'TS bar' }); + const theFoo = await Foo.create({ name: 'TS foo', BarId: theBar.id }); + + // All is fine, BarId is correctly filled in the model, due to the create + expect(await theFoo?.getBar()).to.not.be.null; + + // If have a function in my code that gives me the attributes and include automatically. But in some cases, I want to be + // manually able to lazy load a specific relationship + const theFreshFoo = await Foo.findOne({ + where: { + name: theFoo.get("name") + }, + attributes: ["name"] + }) + // And when trying to load the relation, the relationship attribute is missing, so I simply get null + expect(await theFreshFoo?.getBar()).to.not.be.null; }