rds-data
rds-data copied to clipboard
Nullable Types
I am running into an issue that makes it hard to use nullable types. For instance, a table could have an auto-generated ID (UUID or sequential number) and I'd try to match that with a nullable property on an interface: id?: string
.
TS error:
Property 'id' of type 'string | undefined' is not assignable to string index type 'RDSDataParameterValue'.
Code:
import { RDSDataParameters } from 'rds-data/lib/RDSData';
export interface Message extends RDSDataParameters {
id?: string; // error here
message: string;
}
const m: Message = { message: "hi" };
const { data } = await db.query(
`INSERT INTO messages(message)
VALUES(:message)
RETURNING *`,
m,
);
What is the recommended approach here?
@MarkHerhold first and foremost I am excited you are using it and running into a few bumps because it will allow us to harden the library! Thank you.
Next, I have not approached an INSERT like that so I didn't code into it. In the RDSDataResponse
there is a parameter insertId
which has the auto-generated number in it.
Here is an example
const sql = `INSERT INTO User (pk, id, sub, first, last, email, phone, created, modified)
VALUES(null, :id,:sub,:first,:last,:email,:phone,NOW(),NOW())`;
const id = uuid58();
const results = await Db.getInstance().query(sql, { sub, id, first, last, email, phone });
return results.insertId;
We could update the definition of
export type RDSDataParameterValue = string | Buffer | boolean | number | null;
to include undefined
as well.
https://github.com/cbschuld/rds-data/blob/ce47bae4bec99ca0faf2e5c23d8d0e064704f3d2/src/RDSData.ts#L26
Interested in your thoughts after you see the insertId
process.