Skip to content

Commit

Permalink
Merge pull request #518 from damien-schneider/replace-falsy-check-on-…
Browse files Browse the repository at this point in the history
…primary-key-values
  • Loading branch information
psteinroe authored Nov 6, 2024
2 parents 3ce09a8 + e9f49c9 commit e6502c4
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/six-timers-turn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@supabase-cache-helpers/postgrest-core": patch
---

fix update fetcher when primary key value is equal to false or 0
3 changes: 2 additions & 1 deletion packages/postgrest-core/src/update-fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ export const buildUpdateFetcher =
let filterBuilder = qb.update(payload as any, opts); // todo fix type;
for (const key of primaryKeys) {
const value = input[key];
if (!value)
// The value can be 0 or false, so we need to check if it's null or undefined instead of falsy
if (value === null || value === undefined)
throw new Error(`Missing value for primary key ${String(key)}`);
filterBuilder = filterBuilder.eq(key as string, value);
}
Expand Down
36 changes: 36 additions & 0 deletions packages/postgrest-core/tests/update-fetcher.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,4 +147,40 @@ describe('update', () => {
.maybeSingle();
expect(data?.username).toEqual(`${testRunPrefix}-username-4`);
});

it('should not throw error when primary key value is false', async () => {
const qb = {
update: vi.fn().mockReturnThis(),
eq: vi.fn().mockReturnThis(),
select: vi.fn().mockReturnThis(),
throwOnError: vi.fn().mockReturnThis(),
single: vi.fn().mockResolvedValue({ data: null }),
};

await expect(
buildUpdateFetcher(qb as any, ['is_active'], {
stripPrimaryKeys: false,
queriesForTable: () => [],
})({ is_active: false, username: 'testuser' }),
).resolves.not.toThrow();
expect(qb.eq).toHaveBeenCalledWith('is_active', false);
});

it('should not throw error when primary key value is 0', async () => {
const qb = {
update: vi.fn().mockReturnThis(),
eq: vi.fn().mockReturnThis(),
select: vi.fn().mockReturnThis(),
throwOnError: vi.fn().mockReturnThis(),
single: vi.fn().mockResolvedValue({ data: null }),
};

await expect(
buildUpdateFetcher(qb as any, ['id'], {
stripPrimaryKeys: false,
queriesForTable: () => [],
})({ id: 0, username: 'testuser' }),
).resolves.not.toThrow();
expect(qb.eq).toHaveBeenCalledWith('id', 0);
});
});

0 comments on commit e6502c4

Please sign in to comment.