11import { ObjectId , type Filter , type MatchKeysAndValues , type OptionalId , type OptionalUnlessRequiredId , type WithId } from 'mongodb' ;
22import { getCollection } from '../utils/db' ;
3- import type { CollectionName , EntityPayload , UpsertResult } from './types' ;
3+ import type { BaseExistingEntity , CollectionName , EntityPayload , UpsertResult } from './types' ;
44import { DataError } from './errors' ;
55
66export const upsertEntityByCondition = async < T extends OptionalId < unknown > > (
@@ -24,22 +24,28 @@ export const upsertEntityByCondition = async <T extends OptionalId<unknown>>(
2424 } ;
2525}
2626
27- export async function upsertEntity < T extends WithId < unknown > > ( collectionName : CollectionName , entity : EntityPayload < T > ) : Promise < WithId < T > > {
27+ export async function upsertEntity < T extends BaseExistingEntity > ( collectionName : CollectionName , entity : EntityPayload < T > ) : Promise < WithId < T > > {
2828 const collection = getCollection < T > ( collectionName ) ;
2929 const { _id : entityId , ...entityData } = entity ;
3030
3131 if ( entityId ) {
3232 const updatedEntity = await collection . findOneAndUpdate (
3333 { _id : new ObjectId ( entityId ) as Filter < T > } ,
34- { $set : entityData as Partial < T > } ,
34+ {
35+ $set : entityData as Partial < T > ,
36+ } ,
3537 { returnDocument : "after" }
3638 ) ;
3739 if ( ! updatedEntity ) {
3840 throw new DataError ( 404 , `${ collectionName } : entitiy id: '${ entity . _id } ' not found` ) ;
3941 }
4042 return updatedEntity ;
4143 } else {
42- const result = await collection . insertOne ( entity as OptionalUnlessRequiredId < T > ) ;
43- return { ...entity , _id : result . insertedId } as WithId < T > ;
44+ const entityPayload = {
45+ ...entity as OptionalUnlessRequiredId < T > ,
46+ createdAt : new Date ( ) ,
47+ } ;
48+ const result = await collection . insertOne ( entityPayload ) ;
49+ return { ...entityPayload , _id : result . insertedId } as WithId < T > ;
4450 }
4551}
0 commit comments