@@ -5,8 +5,13 @@ import { basename } from 'node:path'
55import { Glob } from 'bun'
66import { consola } from 'consola'
77import { drizzle } from 'drizzle-orm/bun-sqlite'
8+ import type { SQLiteTable , TableConfig } from 'drizzle-orm/sqlite-core'
89import { parse } from 'smol-toml'
910import * as schema from '#~/schema'
11+
12+ import type { Asset } from '../collections/$schemas/.types/assets'
13+ import type { Author } from '../collections/$schemas/.types/authors'
14+
1015const require = createRequire ( import . meta. url )
1116
1217type DrizzleKitApi = typeof import ( 'drizzle-kit/api' )
@@ -41,27 +46,43 @@ for (const stmt of createStatements) {
4146
4247consola . success ( 'Database initialized\n' )
4348
44- consola . start ( 'Importing assets' )
49+ const scan = ( path : string ) => new Glob ( path ) . scan ( )
4550
46- import type { Asset } from '../collections/$schemas/.types/assets'
51+ const importCollection = async < CollectionSchema , DatabaseSchema extends SQLiteTable < TableConfig > > (
52+ name : string ,
53+ schema : DatabaseSchema ,
54+ mapper : ( schema : CollectionSchema , id : string ) => DatabaseSchema [ '$inferInsert' ] ,
55+ ) => {
56+ consola . start ( `Importing ${ name } ` )
4757
48- const scan = ( path : string ) => new Glob ( path ) . scan ( )
58+ const statements = [ ]
4959
50- const statements = [ ]
60+ for await ( const filePath of scan ( `./collections/${ name } /**/*.toml` ) ) {
61+ const id = basename ( filePath , '.toml' )
62+ const data = parse ( await readFile ( filePath , 'utf-8' ) ) as unknown as CollectionSchema
5163
52- for await ( const filePath of scan ( './collections/assets/**/*.toml' ) ) {
53- const id = basename ( filePath , '.toml' )
54- const data = parse ( await readFile ( filePath , 'utf-8' ) ) as unknown as Asset
64+ statements . push ( db . insert ( schema ) . values ( mapper ( data , id ) ) )
65+ }
5566
56- statements . push (
57- db . insert ( schema . assets ) . values ( {
58- id,
59- name : data . name ,
60- reference : data . reference ,
61- } ) ,
62- )
67+ return Promise . all ( statements ) . then ( ( ) => consola . success ( `Imported ${ name } \n` ) )
6368}
6469
65- await Promise . all ( statements )
70+ await importCollection < Asset , typeof schema . assets > (
71+ 'assets' ,
72+ schema . assets ,
73+ ( { name, reference } , id ) => ( {
74+ id,
75+ name,
76+ reference,
77+ } ) ,
78+ )
6679
67- consola . success ( 'Imported assets\n' )
80+ await importCollection < Author , typeof schema . authors > (
81+ 'authors' ,
82+ schema . authors ,
83+ ( { name, otherNames } , id ) => ( {
84+ id,
85+ name,
86+ otherNames,
87+ } ) ,
88+ )
0 commit comments