Last active
March 2, 2025 21:20
-
-
Save VIEWVIEWVIEW/be2b557498b81e83dca8e7ba9cb9614f to your computer and use it in GitHub Desktop.
A simple wrapper around the sql function of postgres.js to emulate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import postgres from "postgres"; | |
| const sql = postgres(process.env.POSTGRES_URL!, { | |
| transform: postgres.camel | |
| }); | |
| async function gosql<T extends object>(strings: TemplateStringsArray, ...values: any[]): Promise<[RowList<T[]> | [], PostgresError | null]> { | |
| try { | |
| const result = await sql<T[]>(strings, ...values); | |
| return [result, null]; | |
| } catch (error) { | |
| return [[], error as PostgresError]; | |
| } | |
| } | |
| export { gosql }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const [[user], sqlError] = await gosql<User[]>` | |
| INSERT into users ( | |
| email, | |
| username, | |
| hashedPassword, | |
| vat_location, | |
| address | |
| ) | |
| values ( | |
| ${values.email || null}, | |
| ${values.username}, | |
| ${hashedPassword}, | |
| ${values.vatLocation}, | |
| ${values.address || null} | |
| ) | |
| returning *; | |
| ` | |
| console.log(user, sqlError); | |
| if (sqlError) { | |
| // Handle specific database errors by code and constraint name | |
| if (sqlError.code === "23505") { // PostgreSQL unique violation code | |
| // Check which constraint was violated based on constraint name | |
| if (sqlError.constraint_name === "users_email_key") { | |
| errors.email = t("errors.emailInUse"); | |
| } else if (sqlError.constraint_name === "users_username_key") { | |
| errors.username = t("errors.usernameInUse"); | |
| } else { | |
| console.log(sqlError) | |
| // Unknown constraint violation | |
| errors.unknownReason = t("errors.unknownError"); | |
| } | |
| return { errors }; | |
| } | |
| // Generic database error (not a constraint violation) | |
| errors.unknownReason = t("errors.unknownError"); | |
| return { errors }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment