I want to:
- Insert into database, get an id from that, then
- insert another set of data and get an id from that, and finally
- insert both id's into a mapping table.
Within one transaction with SQLite it worked, but using Turso edge database the async function returns the id's from the second insert, but won't console.log()
those values within the async function. However, I'm able to console.log()
the value of the first insert:
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;
};
The final insert is not getting the value of the second insert so is not able to map. I tried:
// 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
Got this:
[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)