sqlite 为什么我的异步REST端点返回一个值,而不是console.log()?

hjzp0vay  于 2023-10-23  发布在  SQLite
关注(0)|答案(1)|浏览(144)

我想:
1.插入到数据库中,从中获取一个id,然后
1.插入另一组数据并从中获取一个ID,最后
1.将两个ID插入Map表。
在SQLite的一个事务中,它工作了,但是使用Turso edge数据库,Bifrc函数返回第二次插入的id,但是不会在Bifrc函数中console.log()这些值。但是,我可以console.log()第一个插入的值:

function buildRouter(env: Env): RouterType {
    const router = Router();

    router.post("/api/main-form", async (request) => {
        const db = buildDB(env)
        const formData = await request.json();

        const loadedFormInfo: any = await db.transaction(async (tx) => {
            // Insert data into formDataTable and retrieve auto-incremented ID
            const insertedFormId: any = tx.insert(formDataTable)
                .values({
                    dateOption: formData.dateOption,
                    timeZone: formData.timeZone,
                    utcTime: new Date(formData.utcTime),
                    localTime: formData.localTime,
                    title: formData.title,
                    tag: formData.tag,
                    latitude: formData.latitude,
                    longitude: formData.longitude,
                    createdAt: new Date()
                })
                .returning({formId: formDataTable.id});

            let formId = await insertedFormId.values();
            formId = formId[0].id

            // return formId

            // Insert data into proponentsTable using the retrieved formId
            const proponentsData: Proponent[] = formData.proponents;
            let insertedProponentIds: Number[] = [];
            proponentsData.forEach(async proponent => {
                let insertedProponentId = tx.insert(proponentsTable)
                    .values({
                        formId: formId,
                        team: proponent.team,
                        name: proponent.name,
                        email: proponent.email,
                        createdAt: new Date()
                    }).returning({proponentId: proponentsTable.id});

                let proponentId = await insertedProponentId.values();
                proponentId = proponentId[0].id;
                insertedProponentIds.push(proponentId);
            });

            console.log(insertedProponentIds)  // <--- returns an empty array
            return insertedProponentIds // <--- responds with actual array

// third insert would go here //

        });

        console.log('outside: ', loadedFormInfo)
        const responseBody = JSON.stringify( {'return_val': loadedFormInfo} );
        const response = new Response(responseBody, { status: 200, headers: { 'Content-Type': 'application/json' } });

        return response;
    });

    router.all("*", () => new Response("Not Found.", { status: 404 }));

    return router;
};

最后一次插入没有得到第二次插入的值,因此无法Map。我试过:

// Insert data into proponentsTable using the retrieved formId
const proponentsData: Proponent[] = formData.proponents;
let insertedProponentIds: Number[] = [];
for (const proponent of proponentsData) {
    try {
        const insertedProponentId = await tx.insert(proponentsTable)
            .values({
                formId: formId,
                team: proponent.team,
                name: proponent.name,
                email: proponent.email,
                createdAt: new Date()
            })
            .returning({ proponentId: proponentsTable.id });

        if (insertedProponentId && insertedProponentId[0] && insertedProponentId[0].id) {
            const proponentId = insertedProponentId[0].id;
            insertedProponentIds.push(proponentId);
        } else {
            console.error("Invalid insertedProponentId data:", insertedProponentId);
        }
    } catch (error) {
        console.error("Error inserting proponent:", error);
    }
}

console.log(insertedProponentIds)
return insertedProponentIds

得到这个:

[mf:inf] POST /api/main-form 500 Internal Server Error (757ms)
⎔ Reloading local server...
[mf:inf] Updated and ready on http://127.0.0.1:8787/
Invalid insertedProponentId data: SQLiteInsert {
  session: _LibSQLSession,
  dialect: SQLiteAsyncDialect,
  config: Object,
  run: ,
  all:
  ...
}
Invalid insertedProponentId data: SQLiteInsert {
  session: _LibSQLSession,
  dialect: SQLiteAsyncDialect,
  config: Object,
  run: ,
  all:
  ...
}
Array(0) [  ]
outside:  Array(0) [  ]
[mf:inf] POST /api/main-form 200 OK (49ms)
xt0899hw

xt0899hw1#

我是这样做的:

// Insert data into proponentsTable using the retrieved formId
const proponentsData: Proponent[] = formData.proponents;
let insertedProponentIds: Number[] = [];
for (const proponent of proponentsData) {
    try {
        let insertedProponentId = await tx.insert(proponentsTable)
            .values({
                formId: formId,
                team: proponent.team,
                name: proponent.name,
                email: proponent.email,
                createdAt: new Date()
            }).returning({ proponentId: proponentsTable.id });

        let proponentId = await insertedProponentId.values();
        // proponentId = proponentId.map(proponent => proponent.id);
        proponentId = proponentId[0].id
        insertedProponentIds.push(proponentId);
    } catch (error) {
        console.error("Error inserting proponent:", error);
        throw error;
    }
}

console.log(insertedProponentIds)
return insertedProponentIds

相关问题