Skip to content

Commit

Permalink
feat: implement on_conflict (#113)
Browse files Browse the repository at this point in the history
  • Loading branch information
izqalan authored Oct 2, 2020
1 parent f887ed4 commit 3a902b3
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,17 @@ export class PostgrestQueryBuilder<T> extends PostgrestBuilder<T> {
*
* @param values The values to insert.
* @param upsert If `true`, performs an UPSERT.
* @param onConflict By specifying the `on_conflict` query parameter, you can make UPSERT work on a column(s) that has a UNIQUE constraint.
*/
insert(values: Partial<T> | Partial<T>[], { upsert = false } = {}): PostgrestBuilder<T> {
insert(
values: Partial<T> | Partial<T>[],
{ upsert = false, onConflict }: { upsert?: boolean; onConflict?: string } = {}
): PostgrestBuilder<T> {
this.method = 'POST'
this.headers['Prefer'] = upsert
? 'return=representation,resolution=merge-duplicates'
: 'return=representation'
if (upsert && onConflict !== undefined) this.url.searchParams.set('on_conflict', onConflict)
this.body = values
return this
}
Expand Down
26 changes: 26 additions & 0 deletions test/__snapshots__/basic.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,32 @@ Object {
}
`;

exports[`on_conflict insert 1`] = `
Object {
"body": Array [
Object {
"age_range": "[20,30)",
"catchphrase": "'fat' 'rat'",
"data": null,
"status": "ONLINE",
"username": "dragarcia",
},
],
"data": Array [
Object {
"age_range": "[20,30)",
"catchphrase": "'fat' 'rat'",
"data": null,
"status": "ONLINE",
"username": "dragarcia",
},
],
"error": null,
"status": 201,
"statusText": "Created",
}
`;

exports[`stored procedure 1`] = `
Object {
"body": "ONLINE",
Expand Down
7 changes: 7 additions & 0 deletions test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ test('switch schema', async () => {
expect(res).toMatchSnapshot()
})

test('on_conflict insert', async () => {
const res = await postgrest
.from('users')
.insert({ username: 'dragarcia' }, { upsert: true, onConflict: 'username' })
expect(res).toMatchSnapshot()
})

describe('basic insert, update, delete', () => {
test('basic insert', async () => {
let res = await postgrest
Expand Down

0 comments on commit 3a902b3

Please sign in to comment.