How to use the Batch API?

Hi, I am using Turso and have an array of people I need to insert into my database. I've tried via db.insert(people).values(peopleArray) but get an error about too many variables or something so then I looked into the batch API, but this doesnt work either:
db.batch(peopleArray.map(p => db.insert(people).values(p))
db.batch(peopleArray.map(p => db.insert(people).values(p))
But I can do something like this which works for a single entry?
const person = { id: 1, name: "Tester" }
const ins = db.insert(people).values(person)
db.batch([ins])
const person = { id: 1, name: "Tester" }
const ins = db.insert(people).values(person)
db.batch([ins])
So why can't I do something similar with an array?
Solution:
You could have a helper like this: ```ts function isTuple<T extends any[]>(array: T): T is [T, ...T[]] { return array.length > 0; }...
Jump to solution
3 Replies
Angelelz
Angelelz12mo ago
db.batch accepts a tuple with at least 1 item. The shape is [T, ...T[]] Typescript is complaining because it can't statically verify that there's at least one item in that array
Solution
Angelelz
Angelelz12mo ago
You could have a helper like this:
function isTuple<T extends any[]>(array: T): T is [T, ...T[]] {
return array.length > 0;
}
function isTuple<T extends any[]>(array: T): T is [T, ...T[]] {
return array.length > 0;
}
With that you can please the compiler
BiffBaffBoff
BiffBaffBoffOP12mo ago
Hiya, thanks for the reply but that still doesnt work:
function isTuple<T>(array: T[]): array is [T, ...T[]] {
return array.length > 0
}
function isTuple<T>(array: T[]): array is [T, ...T[]] {
return array.length > 0
}
Further down:
if (isTuple(peopleArray)) {
const ins = peopleArray.map((p) => db.insert(people).values(p))
await db.batch(ins)
}
if (isTuple(peopleArray)) {
const ins = peopleArray.map((p) => db.insert(people).values(p))
await db.batch(ins)
}
Error: Source provides no match for required element at position 0 in target Ah nvm, sorry it does work, needed to do this:
if (isTuple(ins)) {
await db.batch(ins)
}
if (isTuple(ins)) {
await db.batch(ins)
}
Thanks again for your help
Want results from more Discord servers?
Add your server