Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • database/drizzle/queries/builds.ts

    re09fe6f r9854393  
    495495}
    496496
    497 export async function addNewBuild(db: Database, userId: number, name: string, description: string) {
    498     const [newBuild] = await db
    499         .insert(buildsTable)
    500         .values({
    501             userId: userId,
    502             name: name,
    503             createdAt: new Date().toISOString().split('T')[0],
    504             description: description,
    505             totalPrice: Number(0).toFixed(2),
    506             isApproved: false
    507         })
    508         .returning({
    509             id: buildsTable.id
    510         });
    511 
    512     return newBuild?.id ?? null;
     497export async function addNewBuild(db: Database, userId: number, name: string, description: string, componentIds: number[]) {
     498    return db.transaction(async (tx) => {
     499        const components = await tx
     500            .select({
     501                price:  componentsTable.price
     502            })
     503            .from(componentsTable)
     504            .where(
     505                inArray(componentsTable.id, componentIds)
     506            );
     507
     508        const totalPrice = components.reduce((sum, c) => sum + Number(c.price), 0);
     509
     510        const [newBuild] = await tx
     511            .insert(buildsTable)
     512            .values({
     513                userId: userId,
     514                name: name,
     515                createdAt: new Date().toISOString().split('T')[0],
     516                description: description,
     517                totalPrice: totalPrice.toFixed(2),
     518                isApproved: false
     519            })
     520            .returning({
     521                id: buildsTable.id
     522            });
     523
     524        if(components.length) {
     525            await tx.insert(buildComponentsTable)
     526                .values(
     527                    componentIds.map(componentId => ({
     528                        buildId: newBuild.id,
     529                        componentId: componentId
     530                    }))
     531                );
     532        }
     533
     534        return newBuild?.id ?? null;
     535    });
    513536}
    514537
Note: See TracChangeset for help on using the changeset viewer.