1
1
import type { FastifyInstance } from 'fastify'
2
- import type { Db } from 'mongodb'
2
+ import type { Db , IndexDescription } from 'mongodb'
3
3
import Papr , { type Model , BaseSchema , SchemaOptions } from 'papr'
4
- import { type PaprModels , ModelRegistrationPair } from './types.js'
4
+ import { type PaprModels , ModelRegistrationPair , IndexesRegistrationPair } from './types.js'
5
5
6
6
export const paprHelper = ( fastify : Readonly < FastifyInstance > , db : Db , disableSchemaReconciliation = false ) => {
7
7
const papr = new Papr ( )
@@ -21,14 +21,23 @@ export const paprHelper = (fastify: Readonly<FastifyInstance>, db: Db, disableSc
21
21
return model
22
22
}
23
23
24
+ const registerIndexes = async ( collectionName : string , indexes : readonly IndexDescription [ ] ) => db . collection ( collectionName ) . createIndexes ( indexes as IndexDescription [ ] )
25
+
24
26
return {
25
- register : async ( schemas : ModelRegistrationPair < PaprModels > ) : Promise < PaprModels > =>
26
- Object . fromEntries ( await Promise . all (
27
+ async register ( schemas : ModelRegistrationPair < PaprModels > , indexes : IndexesRegistrationPair [ ] = [ ] ) : Promise < PaprModels > {
28
+ indexes . map ( async ( { collectionIndexes, collectionName} ) => {
29
+ const index = await registerIndexes ( collectionName , collectionIndexes )
30
+ fastify . log . info ( `Indexes to ${ collectionName } created` )
31
+ return index
32
+ } )
33
+
34
+ return Object . fromEntries ( await Promise . all (
27
35
Object . entries ( schemas ) . map ( async ( [ modelName , modelObject ] ) => {
28
36
const model = await registerModel ( modelObject . collectionName , modelObject . collectionSchema )
29
37
fastify . log . info ( `Model ${ modelName } decorated` )
30
38
return [ modelName , model ] as [ string , Model < BaseSchema , SchemaOptions < Partial < BaseSchema > > > ]
31
- } ) ) ) ,
32
-
39
+ } ) ,
40
+ ) )
41
+ } ,
33
42
}
34
43
}
0 commit comments