My web app is architected in such a way that each user has a separate SQLite database with their data in it. I'm trying to get Sequelize to work within that. I'm using SvelteKit which is essentially Node on the back-end.
A user's ID gets passed into a function and then their database is initialized and returned like this:
//--- db.ts ---
export function db(user: string){
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: './db/' user '/Database.sqlite'
})
return sequelize
}
//--- stuff.ts ---
import { db } from 'db'
const stuff = db(userId)
This is all fine and good, but I don't know how to take advance of Model
definitions because I have to be able to pass them the instance of Sequelize
in order for it to be initialized:
//--- field.ts ---
import { DataTypes, Model } from 'sequelize'
class Field extends Model {}
Field.init({
name:{ type: DataTypes.STRING }
}, {
sequelize, // <-- Need the instance
modelName: 'Field'
})
From what I can tell, I have to put my Field
definition inside db.ts
and initialize it every time I access the instance of Sequelize
. But then won't Field
only be available within the context of the db
function?
Is this the proper way to use extreme sharding with Sequelize? Is there a way to define the Field
class generally and then give it the sequelize
instance later?
CodePudding user response:
You just need to wrap all model definition code into a function that has two parameters: sequelize
and DataTypes
. See this question and my answer there to get an idea how to register models and associations.