@@ -2,34 +2,45 @@ import { FieldResolveInput } from 'stucco-js';
2
2
import { BookStatus , resolverFor } from '../zeus/index.js' ;
3
3
import { orm } from '../utils/db/orm.js' ;
4
4
import { GlobalError , errMiddleware , sourceContainUserIdOrThrow } from '../utils/middleware.js' ;
5
+ import { ObjectId } from 'mongodb' ;
5
6
6
7
export const bookService = async ( input : FieldResolveInput ) =>
7
8
resolverFor ( 'UserMutation' , 'bookService' , async ( args , src ) =>
8
9
errMiddleware ( async ( ) => {
9
10
sourceContainUserIdOrThrow ( src ) ;
10
11
const o = await orm ( ) ;
11
- const service = await o ( 'Services' ) . collection . findOneAndUpdate (
12
- { _id : args . input . serviceId , taken : { $ne : true } } ,
12
+
13
+ const services = await Promise . all ( args . input . serviceIds . map ( async ( serviceId ) => {
14
+
15
+ const service = await o ( 'Services' ) . collection . findOneAndUpdate (
16
+ { _id : serviceId , taken : { $ne : true } } ,
13
17
{ $set : { taken : true } } ,
14
18
) ;
15
19
if ( ! service . value ) {
16
- throw new GlobalError ( `service is already taken: ${ args . input . serviceId } ` , import . meta. url ) ;
20
+ throw new GlobalError ( `service is already taken: ${ serviceId } ` , import . meta. url ) ;
17
21
}
18
- const book = await o ( 'Bookings' )
19
- . createWithAutoFields (
20
- '_id' ,
21
- 'createdAt' ,
22
- ) ( {
22
+ console . log ( service ) ;
23
+
24
+ return service . value
25
+ } ) )
26
+ console . log ( services ) ;
27
+
28
+ const books = await o ( 'Bookings' )
29
+ . collection . insertMany ( services . map ( ( service ) => (
30
+ {
31
+ _id : new ObjectId ( ) . toHexString ( ) ,
32
+ createdAt : new Date ( ) ,
23
33
bookerId : src . userId ,
24
- service : args . input . serviceId ,
34
+ service : service . _id ,
25
35
comments : args . input . comments ? args . input . comments : undefined ,
26
- status : service . value . neededAccept ? BookStatus . PENDING : BookStatus . ACCEPTED ,
27
- } )
28
- . then ( async ( c ) => await o ( 'Bookings' ) . collection . findOne ( { _id : c . insertedId } ) ) ;
29
- if ( ! book ) {
36
+ status : service . neededAccept ? BookStatus . PENDING : BookStatus . ACCEPTED ,
37
+ } ) ) )
38
+ . then ( async ( c ) => o ( 'Bookings' ) . collection . find ( { _id : { $in : Object . values ( c . insertedIds ) } } ) ?. toArray ( ) ) ;
39
+ if ( ! books ) {
30
40
throw new GlobalError ( 'inserted document is null' , import . meta. url ) ;
31
41
}
32
- return { book : { ...book , service : service . value } } ;
42
+ console . log ( books ) ;
43
+ return { books : await o ( 'Bookings' ) . composeRelated ( books , 'service' , 'Services' , '_id' ) } ;
33
44
} ) ,
34
45
) ( input . arguments , input . source ) ;
35
46
export default bookService ;
0 commit comments