@@ -32,7 +32,7 @@ const schema = new mongoose.Schema<MapModel>({
3232 } ,
3333} ) ;
3434
35- const model = mongoose . model < MapModel > ( 'point' , schema , 'points' , {
35+ export const model = mongoose . model < MapModel > ( 'point' , schema , 'points' , {
3636 overwriteModels : true ,
3737} ) ;
3838
@@ -53,26 +53,31 @@ export async function addPoints(user: string, points: Record<string, number>, ro
5353 return document . toJSON ( ) ;
5454}
5555
56- export async function bulkAddPoints ( bulkData : BulkPointsDataInput , roomId : string ) : Promise < Model [ ] | undefined > {
56+ export async function bulkAddPoints ( bulkData : BulkPointsDataInput , roomId : string ) : Promise < boolean | undefined > {
5757 if ( ! IS_ENABLED . DB ) return ;
58- const lookupIds = Object . keys ( bulkData ) . map ( userId => `${ roomId } -${ userId } ` ) ;
59- const userPoints = await model . find ( { id : { $in : lookupIds } } ) ;
6058 const roomConfig = PSRoomConfigs [ roomId ] . points ! ;
6159
62- const documentsToSave = await Promise . all (
63- Object . values ( bulkData ) . map ( async ( { name, id, points } ) => {
64- const existing = userPoints . find ( document => document . userId === id ) ;
65- const document =
66- existing ?? ( await model . create ( { id : `${ roomId } -${ id } ` , userId : id , name : name ?? id , roomId, points : new Map ( ) } ) ) ;
67- Object . keys ( roomConfig . types ) . forEach ( type => document . points . set ( type , document . points . get ( type ) ?? 0 ) ) ;
68- document . name = name ?? id ;
69- Object . entries ( points ) . forEach ( ( [ type , count ] ) => document . points . set ( type , ( document . points . get ( type ) ?? 0 ) + count ) ) ;
70- return document ;
71- } )
72- ) ;
73-
74- await model . bulkSave ( documentsToSave ) ;
75- return documentsToSave . map ( document => document . toJSON ( ) ) ;
60+ const bulkQueries = Object . values ( bulkData ) . map ( ( { id, name, points } ) => ( {
61+ updateOne : {
62+ filter : { id : `${ roomId } -${ id } ` } ,
63+ update : {
64+ $setOnInsert : {
65+ id : `${ roomId } -${ id } ` ,
66+ roomId,
67+ userId : id ,
68+ ...Object . fromEntries (
69+ roomConfig . priority . filter ( type => typeof points [ type ] !== 'number' ) . map ( type => [ `points.${ type } ` , 0 ] )
70+ ) ,
71+ } ,
72+ $inc : Object . fromEntries ( Object . entries ( points ) . map ( ( [ type , amount ] ) => [ `points.${ type } ` , amount ] ) ) ,
73+ $set : { name : name ?? id } ,
74+ } ,
75+ upsert : true ,
76+ } ,
77+ } ) ) ;
78+
79+ const res = await model . bulkWrite ( bulkQueries ) ;
80+ return res . isOk ( ) ;
7681}
7782
7883export async function getPoints ( user : string , roomId : string ) : Promise < Model | null | undefined > {
0 commit comments