website/src/db/mod.ts

44 lines
1.1 KiB
TypeScript

import { Db, Group } from '@cohabit/ressources_manager/mod.ts'
// Import Datas
import { exists } from '$std/fs/exists.ts'
import { ensureDir } from '$std/fs/mod.ts'
import { User } from '@cohabit/ressources_manager/src/models/mod.ts'
import { MailAddress } from '@cohabit/ressources_manager/types.ts'
import groups from ":src/db/mock/groups.json" with { type: 'json' }
import users from ":src/db/mock/users.json" with { type: 'json' }
await ensureDir('./cache')
const dbPath = './cache/db.sqlite'
const dbExist = await exists(dbPath)
export const db = await Db.init(dbPath)
//! Temp for demo only
if (!dbExist) {
console.log('=============LOAD DB=============')
// Load groups to DB
for (const { name } of groups) {
const group = Group.load({ name })
db.ressource.group.set([group])
}
// Load users to DB
for (const { lastname, firstname, mail, groups: groupNames } of users) {
// Get groups of user
const groups = await db.ressource.group.listRef((group) =>
groupNames.includes(group.name)
)
const user = User.load({
firstname,
lastname,
mail: mail as MailAddress,
groups,
})
db.ressource.user.set([user])
}
}