I have an object with the structure of RsvpData
export interface RsvpData {
guests: Guest[];
email: string;
phone?: string;
extraInfo?: string;
}
export interface Guest {
name: string;
dietaryRequirements: string;
canAttend: string;
}
I want to add a record to the party database with the parties email
, phone
and extraInfo
, I then want to add each guest to the attendees table with a foriegn key of party_id.
I am using vercel's new PostgreSQL database and @vercel/postgresql. I am using the following code.
const formattedGuests = req.body.guests
.map((guest) => {
return `(${guest.name}, ${guest.dietaryRequirements}, ${guest.canAttend})`;
})
.join(",");
try {
await client.sql`WITH inserted_party AS (
INSERT INTO parties (email, phone, extra_info)
VALUES (${req.body.email}, ${req.body.phone}, ${req.body.extraInfo})
RETURNING PartyId
)
INSERT INTO attendees (party_id, name, dietary_requirements, can_attend)
SELECT PartyId, name, dietary_requirements, can_attend
FROM unnest(ARRAY[${formattedGuests}]::guest[]) AS guest(name, dietary_requirements, can_attend),
inserted_party;`;
}
If guests only contains one guest everything works fine, if it contains multiple guests I get the following error message.
malformed record literal: "(user1, No, true),(test, Maybe, false)"
I have a suspicion it is because the sql
method does not know what values to parameterise in the as I am mapping the guests into a string earlier on, but I am unsure if that is correct, or how to resolve it. This may be a question for the Vercel GitHub, but I am also unsure if the SQL is correct.