feat(supabase): animals and relations access layer

animals.ts: POST search with species filter and a probe row, read by id with
explicit columns, create with the optional first client in one call, update,
archive. relations.ts: an animal's relations in one select (voided left out),
create, end, dates, void. Kinds duplicate_relation and already_ended added.
This commit is contained in:
bchanot committed 2026-10-26 17:11:23 +01:00
1 parent 3c2b503fc9
commit e22357630f
7 files changed
+1612 -12

No files matched your search

+235
View File
@@ -0,0 +1,235 @@
import { z } from 'zod'
import type { FaunosteoClient } from './client'
import type { Database, Tables } from './database.types'
import {
RevisionSchema,
type AnimalRelationRole,
type NameCursor,
} from './clients'
import {
failRecord,
parseRecordAnswer,
UUID_PATTERN,
type RecordPage,
} from './records'
/**
* Browser side of the animals of a workspace (contract §5.2, §8.3, §9.3): one
* read by id under RLS with an explicit column list, the POST search, the
* three write RPCs. `create_animal` takes the optional initial relation in the
* same transaction, so an animal and its first client are never half made.
* The database rules decide; every failure is a RecordFailure of a closed kind.
*/
/** Columns the page reads; the derived keys and the request digest stay server-side. */
export const ANIMAL_COLUMNS =
'id, name, species_id, species_detail, sex, breed, birth_year, birth_date, revision, archived_at, created_at, updated_at'
export type AnimalRecord = Pick<
Tables<'animals'>,
| 'id'
| 'name'
| 'species_id'
| 'species_detail'
| 'sex'
| 'breed'
| 'birth_year'
| 'birth_date'
| 'revision'
| 'archived_at'
| 'created_at'
| 'updated_at'
>
/** The seven fields an animal is created or replaced with; an absent value is null, never ''. */
export type AnimalFields = Pick<
AnimalRecord,
| 'name'
| 'species_id'
| 'species_detail'
| 'sex'
| 'breed'
| 'birth_year'
| 'birth_date'
>
const AnimalListItemSchema = z.object({
id: z.string().uuid(),
name: z.string(),
species_id: z.string(),
species_detail: z.string().nullable(),
sex: z.enum(['male', 'female', 'unknown']),
breed: z.string().nullable(),
birth_year: z.number().int().nullable(),
archived_at: z.string().nullable(),
name_key: z.string(),
/** The first three current owners in name order, archived clients flagged. */
current_owners: z.array(
z.object({
client_id: z.string().uuid(),
display_name: z.string(),
archived: z.boolean(),
}),
),
current_owner_count: z.number().int(),
})
export type AnimalListItem = z.infer<typeof AnimalListItemSchema>
export interface AnimalSearch {
workspaceId: string
/** Trimmed by the server; 0 to 100 characters. */
query: string
/** A species id, or null for every species. */
speciesId: string | null
archived: boolean
/** 1 to 99; one more row is asked to know whether a next page exists. */
pageSize?: number
after?: NameCursor | null
}
/** One page of `search_animals` (POST: the term stays out of the URL). */
export async function searchAnimals(
client: FaunosteoClient,
search: AnimalSearch,
): Promise<RecordPage<AnimalListItem, NameCursor>> {
const size = search.pageSize ?? 25
const { data, error, status } = await client.rpc('search_animals', {
workspace_id: search.workspaceId,
query: search.query,
species_filter: search.speciesId ?? undefined,
archived: search.archived,
page_size: size + 1,
after_name_key: search.after?.nameKey,
after_id: search.after?.id,
})
if (error) failRecord(error, status)
const found = parseRecordAnswer(z.array(AnimalListItemSchema), data)
const rows = found.slice(0, size)
const last = rows.at(-1)
return {
rows,
next:
found.length > size && last
? { nameKey: last.name_key, id: last.id }
: null,
}
}
/** The animal, or null for an unknown id and for an id of another workspace alike. */
export async function fetchAnimalRecord(
client: FaunosteoClient,
animalId: string,
): Promise<AnimalRecord | null> {
if (!UUID_PATTERN.test(animalId)) return null
const { data, error, status } = await client
.from('animals')
.select(ANIMAL_COLUMNS)
.eq('id', animalId)
.maybeSingle()
if (error) failRecord(error, status)
return data
}
/** The client the animal is linked to at creation, with an explicit role. */
export interface InitialRelation {
clientId: string
relationRole: AnimalRelationRole
/** YYYY-MM-DD when known, else null (never filled by default). */
startedOn: string | null
}
export interface CreateAnimalInput {
workspaceId: string
/** One per creation intent, sent again on a retry: the server answers the first animal. */
requestId: string
fields: AnimalFields
relation: InitialRelation | null
}
const CreatedAnimalSchema = z.object({
id: z.string().uuid(),
revision: z.number().int(),
relation_id: z.string().uuid().nullable(),
})
/** Years and dates travel as text: the RPC parses them and answers invalid_input on a bad one. */
const yearText = (year: number | null) =>
year === null ? undefined : String(year)
export async function createAnimalRecord(
client: FaunosteoClient,
input: CreateAnimalInput,
): Promise<{ id: string; revision: number; relationId: string | null }> {
const f = input.fields
const r = input.relation
const { data, error, status } = await client.rpc('create_animal', {
workspace_id: input.workspaceId,
create_request_id: input.requestId,
name: f.name,
species_id: f.species_id,
sex: f.sex,
species_detail: f.species_detail ?? undefined,
breed: f.breed ?? undefined,
birth_year: yearText(f.birth_year),
birth_date: f.birth_date ?? undefined,
client_id: r?.clientId,
relation_role: r?.relationRole,
started_on: r?.startedOn ?? undefined,
})
if (error) failRecord(error, status)
const created = parseRecordAnswer(CreatedAnimalSchema, data)
return {
id: created.id,
revision: created.revision,
relationId: created.relation_id,
}
}
type UpdateAnimalArgs = Database['public']['Functions']['update_animal']['Args']
export interface UpdateAnimalInput {
animalId: string
expectedRevision: number
fields: AnimalFields
}
/** Replaces the seven fields at `expectedRevision`; a stale revision is `conflict`. */
export async function updateAnimalRecord(
client: FaunosteoClient,
input: UpdateAnimalInput,
): Promise<{ revision: number }> {
const f = input.fields
// The update RPC has no defaults: every field is sent, null included (see
// updateClientRecord for why the generated type is widened this way).
const args = {
animal_id: input.animalId,
expected_revision: input.expectedRevision,
name: f.name,
species_id: f.species_id,
sex: f.sex,
species_detail: f.species_detail,
breed: f.breed,
birth_year: f.birth_year === null ? null : String(f.birth_year),
birth_date: f.birth_date,
} satisfies { [K in keyof UpdateAnimalArgs]: UpdateAnimalArgs[K] | null }
const { data, error, status } = await client.rpc(
'update_animal',
args as UpdateAnimalArgs,
)
if (error) failRecord(error, status)
return parseRecordAnswer(RevisionSchema, data)
}
/** Archives or restores; the relations are kept either way (contract §7.1). */
export async function setAnimalArchived(
client: FaunosteoClient,
animalId: string,
archived: boolean,
): Promise<{ revision: number }> {
const { data, error, status } = await client.rpc('set_animal_archived', {
animal_id: animalId,
archived,
})
if (error) failRecord(error, status)
return parseRecordAnswer(RevisionSchema, data)
}
+8 -12
View File
@@ -3,6 +3,7 @@ import type { FaunosteoClient } from './client'
import type { Database, Enums, Tables } from './database.types'
import {
failRecord,
parseRecordAnswer,
RecordFailure,
UUID_PATTERN,
type RecordPage,
@@ -132,13 +133,8 @@ const CreatedSchema = z.object({
id: z.string().uuid(),
revision: z.number().int(),
})
const RevisionSchema = z.object({ revision: z.number().int() })
function parsed<T>(schema: z.ZodType<T>, data: unknown): T {
const result = schema.safeParse(data)
if (!result.success) throw new RecordFailure('unavailable', result.error)
return result.data
}
/** The answer of every update, archive and relation write RPC. */
export const RevisionSchema = z.object({ revision: z.number().int() })
export interface CreateClientInput {
workspaceId: string
@@ -166,7 +162,7 @@ export async function createClientRecord(
country: f.country ?? undefined,
})
if (error) failRecord(error, status)
return parsed(CreatedSchema, data)
return parseRecordAnswer(CreatedSchema, data)
}
type UpdateClientArgs = Database['public']['Functions']['update_client']['Args']
@@ -204,7 +200,7 @@ export async function updateClientRecord(
args as UpdateClientArgs,
)
if (error) failRecord(error, status)
return parsed(RevisionSchema, data)
return parseRecordAnswer(RevisionSchema, data)
}
export async function setClientArchived(
@@ -217,7 +213,7 @@ export async function setClientArchived(
archived,
})
if (error) failRecord(error, status)
return parsed(RevisionSchema, data)
return parseRecordAnswer(RevisionSchema, data)
}
const ArchivePreviewSchema = z.object({
@@ -235,7 +231,7 @@ export async function fetchClientArchivePreview(
client_id: clientId,
})
if (error) failRecord(error, status)
return parsed(ArchivePreviewSchema, data)
return parseRecordAnswer(ArchivePreviewSchema, data)
}
const ClientAnimalSchema = z.object({
@@ -274,7 +270,7 @@ export async function listClientAnimals(
after_id: options.after?.relationId,
})
if (error) failRecord(error, status)
const rows = parsed(z.array(ClientAnimalSchema), data)
const rows = parseRecordAnswer(z.array(ClientAnimalSchema), data)
const page = rows.slice(0, size)
const last = page.at(-1)
return {
+29
View File
@@ -93,6 +93,8 @@ export {
RECORD_FAILURE_KINDS,
RecordFailure,
classifyRecordError,
parseRecordAnswer,
UUID_PATTERN,
type RecordFailureKind,
type RecordPage,
} from './records'
@@ -121,6 +123,33 @@ export {
type RelationCursor,
type UpdateClientInput,
} from './clients'
export {
ANIMAL_COLUMNS,
createAnimalRecord,
fetchAnimalRecord,
searchAnimals,
setAnimalArchived,
updateAnimalRecord,
type AnimalFields,
type AnimalListItem,
type AnimalRecord,
type AnimalSearch,
type CreateAnimalInput,
type InitialRelation,
type UpdateAnimalInput,
} from './animals'
export {
ANIMAL_RELATION_COLUMNS,
createAnimalClientRelation,
endAnimalClientRelation,
fetchAnimalRelations,
updateAnimalClientRelation,
voidAnimalClientRelation,
type AnimalRelationItem,
type CreateRelationInput,
type EndRelationInput,
type UpdateRelationDatesInput,
} from './relations'
export {
ANIMAL_FIELD_LIMITS,
BIRTH_YEAR_MIN,
+13
View File
@@ -1,3 +1,5 @@
import type { z } from 'zod'
/**
* Closed failure kinds of the V1-1 record reads and RPCs (clients, animals,
* relations): contract docs/development/V1-1_OWNERS_ANIMALS.md §9.4. The
@@ -14,6 +16,8 @@ export const RECORD_FAILURE_KINDS = [
'limit_reached',
'rate_limited',
'invalid_input',
'duplicate_relation',
'already_ended',
'session_expired',
'network',
'unavailable',
@@ -37,6 +41,8 @@ const RPC_MESSAGE_KINDS: ReadonlySet<string> = new Set([
'limit_reached',
'rate_limited',
'invalid_input',
'duplicate_relation',
'already_ended',
])
interface PostgrestLikeError {
@@ -70,6 +76,13 @@ export function failRecord(error: unknown, status?: number): never {
throw new RecordFailure(classifyRecordError(error, status), error)
}
/** The RPC answer checked against its contract; a different shape is `unavailable`. */
export function parseRecordAnswer<T>(schema: z.ZodType<T>, data: unknown): T {
const result = schema.safeParse(data)
if (!result.success) throw new RecordFailure('unavailable', result.error)
return result.data
}
/** Ids are uuids: anything else is answered as unknown without a request. */
export const UUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+165
View File
@@ -0,0 +1,165 @@
import { z } from 'zod'
import type { FaunosteoClient } from './client'
import type { Database } from './database.types'
import { RevisionSchema } from './clients'
import { failRecord, parseRecordAnswer, UUID_PATTERN } from './records'
/**
* Browser side of the relations between an animal and its clients (contract
* §5.3, §8.3, §9.3). The animal page reads them with one select by animal id
* (at most 200 by the cap), the client embedded through the composite foreign
* key; voided relations are left out, as every V1-1 screen leaves them out.
* Writes go through the four relation RPCs only.
*/
const RELATION_ROLES = ['owner', 'keeper', 'contact'] as const
/**
* `ended_at` tells a current relation from a former one; it is a technical
* time, never shown as the end date (`ended_on` is).
*/
export const ANIMAL_RELATION_COLUMNS =
'id, relation_role, started_on, ended_on, ended_at, revision, client:clients!animal_client_relations_client_fk(id, kind, display_name, phone, email, archived_at)'
const AnimalRelationSchema = z.object({
id: z.string().uuid(),
relation_role: z.enum(RELATION_ROLES),
started_on: z.string().nullable(),
ended_on: z.string().nullable(),
ended_at: z.string().nullable(),
revision: z.number().int(),
client: z.object({
id: z.string().uuid(),
kind: z.enum(['person', 'organization']),
display_name: z.string(),
phone: z.string().nullable(),
email: z.string().nullable(),
archived_at: z.string().nullable(),
}),
})
export type AnimalRelationItem = z.infer<typeof AnimalRelationSchema>
/** The cap of relations per animal (contract §10), ended and voided included. */
const RELATIONS_PER_ANIMAL = 200
/** The animal's relations that existed (voided ones left out), in creation order. */
export async function fetchAnimalRelations(
client: FaunosteoClient,
animalId: string,
): Promise<AnimalRelationItem[]> {
if (!UUID_PATTERN.test(animalId)) return []
const { data, error, status } = await client
.from('animal_client_relations')
.select(ANIMAL_RELATION_COLUMNS)
.eq('animal_id', animalId)
.is('voided_at', null)
.order('created_at')
.order('id')
.limit(RELATIONS_PER_ANIMAL)
if (error) failRecord(error, status)
return parseRecordAnswer(z.array(AnimalRelationSchema), data)
}
export interface CreateRelationInput {
animalId: string
clientId: string
/** One per creation intent, sent again on a retry: the server answers the first relation. */
requestId: string
relationRole: (typeof RELATION_ROLES)[number]
/** YYYY-MM-DD when known, else null (never filled by default). */
startedOn: string | null
}
const CreatedSchema = z.object({
id: z.string().uuid(),
revision: z.number().int(),
})
/** A current relation between an active animal and an active client of one workspace. */
export async function createAnimalClientRelation(
client: FaunosteoClient,
input: CreateRelationInput,
): Promise<{ id: string; revision: number }> {
const { data, error, status } = await client.rpc(
'create_animal_client_relation',
{
animal_id: input.animalId,
client_id: input.clientId,
create_request_id: input.requestId,
relation_role: input.relationRole,
started_on: input.startedOn ?? undefined,
},
)
if (error) failRecord(error, status)
return parseRecordAnswer(CreatedSchema, data)
}
export interface EndRelationInput {
relationId: string
expectedRevision: number
/** The real end date when known; null records the end without one. */
endedOn: string | null
}
/** Ends a current relation: it stays as a former one, with its dates. */
export async function endAnimalClientRelation(
client: FaunosteoClient,
input: EndRelationInput,
): Promise<{ revision: number }> {
const { data, error, status } = await client.rpc(
'end_animal_client_relation',
{
relation_id: input.relationId,
expected_revision: input.expectedRevision,
ended_on: input.endedOn ?? undefined,
},
)
if (error) failRecord(error, status)
return parseRecordAnswer(RevisionSchema, data)
}
type UpdateRelationArgs =
Database['public']['Functions']['update_animal_client_relation']['Args']
export interface UpdateRelationDatesInput {
relationId: string
expectedRevision: number
startedOn: string | null
/** Only on an ended relation; the server refuses one on a current relation. */
endedOn: string | null
}
/** Corrects the dates; both are sent, an empty one is null (the RPC has no defaults). */
export async function updateAnimalClientRelation(
client: FaunosteoClient,
input: UpdateRelationDatesInput,
): Promise<{ revision: number }> {
const args = {
relation_id: input.relationId,
expected_revision: input.expectedRevision,
started_on: input.startedOn,
ended_on: input.endedOn,
} satisfies { [K in keyof UpdateRelationArgs]: UpdateRelationArgs[K] | null }
const { data, error, status } = await client.rpc(
'update_animal_client_relation',
args as UpdateRelationArgs,
)
if (error) failRecord(error, status)
return parseRecordAnswer(RevisionSchema, data)
}
/** Voids a relation entered by mistake (N4): kept, frozen and shown nowhere; never a deletion. */
export async function voidAnimalClientRelation(
client: FaunosteoClient,
input: { relationId: string; expectedRevision: number },
): Promise<{ revision: number }> {
const { data, error, status } = await client.rpc(
'void_animal_client_relation',
{
relation_id: input.relationId,
expected_revision: input.expectedRevision,
},
)
if (error) failRecord(error, status)
return parseRecordAnswer(RevisionSchema, data)
}
+592
View File
@@ -0,0 +1,592 @@
import {
ANIMAL_COLUMNS,
ANIMAL_RELATION_COLUMNS,
RECORD_FAILURE_KINDS,
RecordFailure,
classifyRecordError,
createAnimalClientRelation,
createAnimalRecord,
endAnimalClientRelation,
fetchAnimalRecord,
fetchAnimalRelations,
parseRecordAnswer,
searchAnimals,
setAnimalArchived,
updateAnimalClientRelation,
updateAnimalRecord,
voidAnimalClientRelation,
type AnimalFields,
type FaunosteoClient,
} from '../src'
import { z } from 'zod'
/**
* Call shapes and closed failure kinds of the animals and relations access
* layer. The argument names are checked by the compiler against the generated
* types; the RPC bodies by supabase/tests/014_animals_relations.sql; the same
* functions run against real PostgREST in tests/sandbox/animals-access.sandbox.ts.
*/
type Answer = { data?: unknown; error?: unknown; status?: number }
function stubClient(answers: { rpc?: Answer; select?: Answer } = {}) {
const rpcCalls: Array<[string, Record<string, unknown>]> = []
const query: Record<string, unknown> = {}
const orders: string[] = []
const settle = (a: Answer = {}) => ({
data: a.data ?? null,
error: a.error ?? null,
status: a.status ?? (a.error ? 400 : 200),
})
const chain = {
select: (cols: string) => ((query.select = cols), chain),
eq: (col: string, value: unknown) => ((query[`eq:${col}`] = value), chain),
is: (col: string, value: unknown) => ((query[`is:${col}`] = value), chain),
order: (col: string) => (orders.push(col), chain),
limit: (n: number) => ((query.limit = n), chain),
maybeSingle: async () => settle(answers.select),
then: (resolve: (v: unknown) => void) => resolve(settle(answers.select)),
}
const client = {
from: (table: string) => ((query.table = table), chain),
rpc: async (name: string, args: Record<string, unknown>) => {
rpcCalls.push([name, args])
return settle(answers.rpc)
},
} as unknown as FaunosteoClient
return { client, rpcCalls, query, orders }
}
const WS = '11111111-1111-4111-8111-111111111111'
const ID = '22222222-2222-4222-8222-222222222222'
const REQUEST = '33333333-3333-4333-8333-333333333333'
const CLIENT = '44444444-4444-4444-8444-444444444444'
const RELATION = '55555555-5555-4555-8555-555555555555'
const fields: AnimalFields = {
name: 'Éclair',
species_id: 'equine',
species_detail: null,
sex: 'female',
breed: null,
birth_year: 2015,
birth_date: null,
}
function listRow(i: number) {
return {
id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
name: `Animal ${i}`,
species_id: 'equine',
species_detail: null,
sex: 'unknown',
breed: null,
birth_year: null,
archived_at: null,
name_key: `animal ${String(i).padStart(3, '0')}`,
current_owners: [],
current_owner_count: 0,
}
}
function relationRow(patch: Record<string, unknown> = {}) {
return {
id: RELATION,
relation_role: 'owner',
started_on: null,
ended_on: null,
ended_at: null,
revision: 1,
client: {
id: CLIENT,
kind: 'person',
display_name: 'Marie Dupont',
phone: null,
email: null,
archived_at: null,
},
...patch,
}
}
async function kindOf(promise: Promise<unknown>) {
try {
await promise
return 'no failure'
} catch (error) {
return error instanceof RecordFailure ? error.kind : 'not a RecordFailure'
}
}
describe('relation failure kinds', () => {
it('are closed kinds of the record failures', () => {
expect(RECORD_FAILURE_KINDS).toContain('duplicate_relation')
expect(RECORD_FAILURE_KINDS).toContain('already_ended')
})
it.each(['duplicate_relation', 'already_ended'])(
'P0001 %s is that kind',
(message) => {
expect(classifyRecordError({ code: 'P0001', message }, 400)).toBe(message)
},
)
it('parseRecordAnswer returns the parsed value or throws unavailable', async () => {
const schema = z.object({ revision: z.number().int() })
expect(parseRecordAnswer(schema, { revision: 2 })).toEqual({ revision: 2 })
expect(
await kindOf(Promise.resolve().then(() => parseRecordAnswer(schema, {}))),
).toBe('unavailable')
})
})
describe('searchAnimals', () => {
it('posts the term, every species when null, one row more than the page', async () => {
const { client, rpcCalls } = stubClient({ rpc: { data: [listRow(1)] } })
const page = await searchAnimals(client, {
workspaceId: WS,
query: 'ecl',
speciesId: null,
archived: false,
})
expect(rpcCalls).toEqual([
[
'search_animals',
{
workspace_id: WS,
query: 'ecl',
species_filter: undefined,
archived: false,
page_size: 26,
after_name_key: undefined,
after_id: undefined,
},
],
])
expect(page).toEqual({ rows: [listRow(1)], next: null })
})
it('sends the species filter and the cursor; the probe row becomes next', async () => {
const rows = Array.from({ length: 11 }, (_, i) => listRow(i + 1))
const { client, rpcCalls } = stubClient({ rpc: { data: rows } })
const page = await searchAnimals(client, {
workspaceId: WS,
query: '',
speciesId: 'canine',
archived: true,
pageSize: 10,
after: { nameKey: 'animal 000', id: ID },
})
expect(rpcCalls[0][1]).toMatchObject({
species_filter: 'canine',
archived: true,
page_size: 11,
after_name_key: 'animal 000',
after_id: ID,
})
expect(page.rows).toHaveLength(10)
expect(page.next).toEqual({ nameKey: rows[9].name_key, id: rows[9].id })
})
it('refuses an answer of another shape as unavailable', async () => {
const { client } = stubClient({ rpc: { data: [{ id: ID }] } })
expect(
await kindOf(
searchAnimals(client, {
workspaceId: WS,
query: '',
speciesId: null,
archived: false,
}),
),
).toBe('unavailable')
})
})
describe('fetchAnimalRecord', () => {
it('reads one animal by id with the explicit column list', async () => {
const { client, query } = stubClient({ select: { data: { id: ID } } })
expect(await fetchAnimalRecord(client, ID)).toEqual({ id: ID })
expect(query).toEqual({
table: 'animals',
select: ANIMAL_COLUMNS,
'eq:id': ID,
})
expect(ANIMAL_COLUMNS).not.toContain('*')
expect(ANIMAL_COLUMNS).not.toContain('create_request')
expect(ANIMAL_COLUMNS).not.toContain('workspace_id')
})
it('answers null for an id that is not a uuid, without a request', async () => {
const { client, query } = stubClient()
expect(await fetchAnimalRecord(client, 'not-a-uuid')).toBeNull()
expect(query.table).toBeUndefined()
})
it('maps a lost answer to network and an expired session to session_expired', async () => {
const lost = stubClient({
select: { error: { code: '', message: 'FetchError' }, status: 0 },
})
expect(await kindOf(fetchAnimalRecord(lost.client, ID))).toBe('network')
const expired = stubClient({
select: {
error: { code: 'PGRST301', message: 'JWT expired' },
status: 401,
},
})
expect(await kindOf(fetchAnimalRecord(expired.client, ID))).toBe(
'session_expired',
)
})
})
describe('animal writes', () => {
it('creates without relation: optionals left to their defaults, year as text', async () => {
const { client, rpcCalls } = stubClient({
rpc: { data: { id: ID, revision: 1, relation_id: null } },
})
expect(
await createAnimalRecord(client, {
workspaceId: WS,
requestId: REQUEST,
fields,
relation: null,
}),
).toEqual({ id: ID, revision: 1, relationId: null })
expect(rpcCalls[0]).toEqual([
'create_animal',
{
workspace_id: WS,
create_request_id: REQUEST,
name: 'Éclair',
species_id: 'equine',
sex: 'female',
species_detail: undefined,
breed: undefined,
birth_year: '2015',
birth_date: undefined,
client_id: undefined,
relation_role: undefined,
started_on: undefined,
},
])
})
it('creates with an initial relation in the same call', async () => {
const { client, rpcCalls } = stubClient({
rpc: { data: { id: ID, revision: 1, relation_id: RELATION } },
})
const created = await createAnimalRecord(client, {
workspaceId: WS,
requestId: REQUEST,
fields: {
...fields,
species_id: 'other',
species_detail: 'Furet',
birth_year: 2015,
birth_date: '2015-04-12',
},
relation: {
clientId: CLIENT,
relationRole: 'keeper',
startedOn: '2020-01-02',
},
})
expect(created.relationId).toBe(RELATION)
expect(rpcCalls[0][1]).toMatchObject({
species_id: 'other',
species_detail: 'Furet',
birth_year: '2015',
birth_date: '2015-04-12',
client_id: CLIENT,
relation_role: 'keeper',
started_on: '2020-01-02',
})
const noDate = stubClient({
rpc: { data: { id: ID, revision: 1, relation_id: RELATION } },
})
await createAnimalRecord(noDate.client, {
workspaceId: WS,
requestId: REQUEST,
fields: { ...fields, birth_year: null },
relation: { clientId: CLIENT, relationRole: 'owner', startedOn: null },
})
expect(noDate.rpcCalls[0][1]).toMatchObject({
birth_year: undefined,
started_on: undefined,
client_id: CLIENT,
})
})
it('updates with every field, null included, at the expected revision', async () => {
const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 3 } } })
expect(
await updateAnimalRecord(client, {
animalId: ID,
expectedRevision: 2,
fields: { ...fields, birth_year: null },
}),
).toEqual({ revision: 3 })
expect(rpcCalls[0]).toEqual([
'update_animal',
{
animal_id: ID,
expected_revision: 2,
name: 'Éclair',
species_id: 'equine',
sex: 'female',
species_detail: null,
breed: null,
birth_year: null,
birth_date: null,
},
])
const withYear = stubClient({ rpc: { data: { revision: 3 } } })
await updateAnimalRecord(withYear.client, {
animalId: ID,
expectedRevision: 2,
fields,
})
expect(withYear.rpcCalls[0][1].birth_year).toBe('2015')
})
it('archives and restores through set_animal_archived', async () => {
const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } })
expect(await setAnimalArchived(client, ID, false)).toEqual({ revision: 2 })
expect(rpcCalls[0]).toEqual([
'set_animal_archived',
{ animal_id: ID, archived: false },
])
})
it.each([
'conflict',
'request_conflict',
'archived',
'rate_limited',
'limit_reached',
'invalid_input',
])('a %s refusal reaches the caller as that kind', async (message) => {
const { client } = stubClient({
rpc: { error: { code: 'P0001', message } },
})
expect(
await kindOf(
updateAnimalRecord(client, {
animalId: ID,
expectedRevision: 1,
fields,
}),
),
).toBe(message)
})
it('an unknown or foreign id is not_found; a created answer of another shape is unavailable', async () => {
const { client } = stubClient({
rpc: { error: { code: '42501', message: 'not_found' }, status: 403 },
})
expect(await kindOf(setAnimalArchived(client, ID, true))).toBe('not_found')
const odd = stubClient({ rpc: { data: { id: ID, revision: 1 } } })
expect(
await kindOf(
createAnimalRecord(odd.client, {
workspaceId: WS,
requestId: REQUEST,
fields,
relation: null,
}),
),
).toBe('unavailable')
})
})
describe('fetchAnimalRelations', () => {
it('reads by animal id, voided left out, explicit columns, bounded and ordered', async () => {
const { client, query, orders } = stubClient({
select: { data: [relationRow()] },
})
expect(await fetchAnimalRelations(client, ID)).toEqual([relationRow()])
expect(query).toEqual({
table: 'animal_client_relations',
select: ANIMAL_RELATION_COLUMNS,
'eq:animal_id': ID,
'is:voided_at': null,
limit: 200,
})
expect(orders).toEqual(['created_at', 'id'])
expect(ANIMAL_RELATION_COLUMNS).not.toContain('*')
expect(ANIMAL_RELATION_COLUMNS).not.toContain('create_request')
})
it('answers [] for an id that is not a uuid, without a request', async () => {
const { client, query } = stubClient()
expect(await fetchAnimalRelations(client, 'nope')).toEqual([])
expect(query.table).toBeUndefined()
})
it('refuses a row without its client as unavailable, maps failures', async () => {
const { client } = stubClient({
select: { data: [relationRow({ client: null })] },
})
expect(await kindOf(fetchAnimalRelations(client, ID))).toBe('unavailable')
const lost = stubClient({
select: { error: { message: 'TypeError: Failed to fetch' }, status: 0 },
})
expect(await kindOf(fetchAnimalRelations(lost.client, ID))).toBe('network')
})
})
describe('relation writes', () => {
it('creates with the request id; a missing start date is left to its default', async () => {
const { client, rpcCalls } = stubClient({
rpc: { data: { id: RELATION, revision: 1 } },
})
expect(
await createAnimalClientRelation(client, {
animalId: ID,
clientId: CLIENT,
requestId: REQUEST,
relationRole: 'contact',
startedOn: null,
}),
).toEqual({ id: RELATION, revision: 1 })
expect(rpcCalls[0]).toEqual([
'create_animal_client_relation',
{
animal_id: ID,
client_id: CLIENT,
create_request_id: REQUEST,
relation_role: 'contact',
started_on: undefined,
},
])
})
it('ends with or without a date', async () => {
const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } })
await endAnimalClientRelation(client, {
relationId: RELATION,
expectedRevision: 1,
endedOn: null,
})
await endAnimalClientRelation(client, {
relationId: RELATION,
expectedRevision: 1,
endedOn: '2024-05-01',
})
expect(rpcCalls).toEqual([
[
'end_animal_client_relation',
{ relation_id: RELATION, expected_revision: 1, ended_on: undefined },
],
[
'end_animal_client_relation',
{ relation_id: RELATION, expected_revision: 1, ended_on: '2024-05-01' },
],
])
})
it('corrects the dates sending both, null included', async () => {
const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 3 } } })
expect(
await updateAnimalClientRelation(client, {
relationId: RELATION,
expectedRevision: 2,
startedOn: '2020-01-01',
endedOn: null,
}),
).toEqual({ revision: 3 })
expect(rpcCalls[0]).toEqual([
'update_animal_client_relation',
{
relation_id: RELATION,
expected_revision: 2,
started_on: '2020-01-01',
ended_on: null,
},
])
})
it('voids at the expected revision', async () => {
const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } })
expect(
await voidAnimalClientRelation(client, {
relationId: RELATION,
expectedRevision: 1,
}),
).toEqual({ revision: 2 })
expect(rpcCalls[0]).toEqual([
'void_animal_client_relation',
{ relation_id: RELATION, expected_revision: 1 },
])
})
it.each([
['duplicate_relation', 'P0001', 400],
['already_ended', 'P0001', 400],
['conflict', 'P0001', 400],
['archived', 'P0001', 400],
['limit_reached', 'P0001', 400],
['not_found', '42501', 403],
])(
'a %s refusal reaches the caller as that kind',
async (message, code, status) => {
const { client } = stubClient({
rpc: { error: { code, message }, status },
})
expect(
await kindOf(
createAnimalClientRelation(client, {
animalId: ID,
clientId: CLIENT,
requestId: REQUEST,
relationRole: 'owner',
startedOn: null,
}),
),
).toBe(message)
expect(
await kindOf(
endAnimalClientRelation(client, {
relationId: RELATION,
expectedRevision: 1,
endedOn: null,
}),
),
).toBe(message)
},
)
it('an expired session, a lost answer and an odd answer are closed kinds', async () => {
const expired = stubClient({
rpc: { error: { code: 'PGRST301', message: 'JWT expired' }, status: 401 },
})
expect(
await kindOf(
voidAnimalClientRelation(expired.client, {
relationId: RELATION,
expectedRevision: 1,
}),
),
).toBe('session_expired')
const lost = stubClient({
rpc: { error: { message: 'TypeError: Failed to fetch' }, status: 0 },
})
expect(
await kindOf(
voidAnimalClientRelation(lost.client, {
relationId: RELATION,
expectedRevision: 1,
}),
),
).toBe('network')
const odd = stubClient({ rpc: { data: { revision: 'x' } } })
expect(
await kindOf(
voidAnimalClientRelation(odd.client, {
relationId: RELATION,
expectedRevision: 1,
}),
),
).toBe('unavailable')
})
})
@@ -0,0 +1,570 @@
/**
* The V1-1.6 access layer (src/animals.ts, src/relations.ts) against the real
* GoTrue and PostgREST of `pnpm db:sandbox`, through supabase-js as the
* browser uses it: the generated argument names, the explicit columns, the
* embedded client of a relation, the keyset pages and every closed failure
* kind come from the real server, not from a stub. Fictitious data only.
*/
import { randomUUID } from 'node:crypto'
import { createClient } from '@supabase/supabase-js'
import {
RecordFailure,
createAnimalClientRelation,
createAnimalRecord,
createClientRecord,
endAnimalClientRelation,
fetchAnimalRecord,
fetchAnimalRelations,
fetchPersonalWorkspaceId,
listClientAnimals,
searchAnimals,
setAnimalArchived,
updateAnimalClientRelation,
updateAnimalRecord,
voidAnimalClientRelation,
type AnimalFields,
type Database,
type FaunosteoClient,
} from '../../src'
import { PASSWORD, confirmedAccount, stack, type Account } from './stack'
const BASE = 'http://sandbox.faunosteo.invalid'
function browserClient(): FaunosteoClient {
const mapped: typeof fetch = (input, init) => {
const url = String(input instanceof Request ? input.url : input)
.replace(`${BASE}/auth/v1`, stack.authUrl)
.replace(`${BASE}/rest/v1`, stack.restUrl)
return fetch(url, init)
}
return createClient<Database>(BASE, stack.anonKey, {
auth: { persistSession: false, autoRefreshToken: false },
global: { fetch: mapped },
})
}
async function signedIn(account: Account): Promise<FaunosteoClient> {
const client = browserClient()
const { error } = await client.auth.signInWithPassword({
email: account.email,
password: PASSWORD,
})
if (error) throw error
return client
}
async function kindOf(promise: Promise<unknown>) {
try {
await promise
return 'no failure'
} catch (error) {
return error instanceof RecordFailure ? error.kind : String(error)
}
}
const animal = (
name: string,
patch: Partial<AnimalFields> = {},
): AnimalFields => ({
name,
species_id: 'equine',
species_detail: null,
sex: 'unknown',
breed: null,
birth_year: null,
birth_date: null,
...patch,
})
describe('animals and relations access layer on the sandbox', () => {
let a: Account
let b: Account
let asA: FaunosteoClient
let asB: FaunosteoClient
let wA: string
let wB: string
async function clientOfA(name: string): Promise<string> {
const { id } = await createClientRecord(asA, {
workspaceId: wA,
requestId: randomUUID(),
fields: {
kind: 'person',
display_name: name,
email: null,
phone: '+33612345678',
address_line1: null,
address_line2: null,
postal_code: null,
city: null,
country: null,
},
})
return id
}
async function animalOfA(name: string): Promise<string> {
return (
await createAnimalRecord(asA, {
workspaceId: wA,
requestId: randomUUID(),
fields: animal(name),
relation: null,
})
).id
}
beforeAll(async () => {
a = await confirmedAccount('animals-a')
b = await confirmedAccount('animals-b')
asA = await signedIn(a)
asB = await signedIn(b)
wA = (await fetchPersonalWorkspaceId(asA, a.id)) as string
wB = (await fetchPersonalWorkspaceId(asB, b.id)) as string
})
it('creates without a relation and reads the explicit columns', async () => {
const fields = animal('Tornado Fictif', {
sex: 'male',
breed: 'Selle français',
birth_year: 2015,
birth_date: '2015-04-12',
})
const created = await createAnimalRecord(asA, {
workspaceId: wA,
requestId: randomUUID(),
fields,
relation: null,
})
expect(created).toMatchObject({ revision: 1, relationId: null })
const record = await fetchAnimalRecord(asA, created.id)
expect(Object.keys(record ?? {}).sort()).toEqual(
[
'archived_at',
'birth_date',
'birth_year',
'breed',
'created_at',
'id',
'name',
'revision',
'sex',
'species_detail',
'species_id',
'updated_at',
].sort(),
)
expect(record).toMatchObject({ ...fields, revision: 1, archived_at: null })
expect(await fetchAnimalRelations(asA, created.id)).toEqual([])
})
it('creates with an initial relation, replays idempotently, refuses a divergent replay', async () => {
const clientId = await clientOfA('Marie Initiale')
const requestId = randomUUID()
const input = {
workspaceId: wA,
requestId,
fields: animal('Furet Fictif', {
species_id: 'other',
species_detail: 'Furet',
}),
relation: {
clientId,
relationRole: 'owner' as const,
startedOn: '2020-01-02',
},
}
const first = await createAnimalRecord(asA, input)
expect(first.relationId).not.toBeNull()
expect(await createAnimalRecord(asA, input)).toEqual(first)
expect(
await kindOf(
createAnimalRecord(asA, {
...input,
fields: animal('Autre Nom', {
species_id: 'other',
species_detail: 'Furet',
}),
}),
),
).toBe('request_conflict')
const relations = await fetchAnimalRelations(asA, first.id)
expect(relations).toEqual([
{
id: first.relationId,
relation_role: 'owner',
started_on: '2020-01-02',
ended_on: null,
ended_at: null,
revision: 1,
client: {
id: clientId,
kind: 'person',
display_name: 'Marie Initiale',
phone: '+33612345678',
email: null,
archived_at: null,
},
},
])
const found = await searchAnimals(asA, {
workspaceId: wA,
query: 'furet fictif',
speciesId: null,
archived: false,
})
expect(found.rows).toHaveLength(1)
expect(found.rows[0]).toMatchObject({
id: first.id,
current_owner_count: 1,
current_owners: [
{
client_id: clientId,
display_name: 'Marie Initiale',
archived: false,
},
],
})
})
it('searches by term, species filter and archived toggle, in pages', async () => {
const c = await confirmedAccount('animals-page')
const asC = await signedIn(c)
const wC = (await fetchPersonalWorkspaceId(asC, c.id)) as string
for (let i = 1; i <= 12; i++) {
await createAnimalRecord(asC, {
workspaceId: wC,
requestId: randomUUID(),
fields: animal(`Cheval ${String(i).padStart(2, '0')}`),
relation: null,
})
}
const dog = await createAnimalRecord(asC, {
workspaceId: wC,
requestId: randomUUID(),
fields: animal('Chien Unique', { species_id: 'canine' }),
relation: null,
})
const one = await searchAnimals(asC, {
workspaceId: wC,
query: 'cheval',
speciesId: 'equine',
archived: false,
pageSize: 10,
})
expect(one.rows).toHaveLength(10)
expect(one.next).not.toBeNull()
const two = await searchAnimals(asC, {
workspaceId: wC,
query: 'cheval',
speciesId: 'equine',
archived: false,
pageSize: 10,
after: one.next,
})
expect(two.rows.map((r) => r.name)).toEqual(['Cheval 11', 'Cheval 12'])
expect(two.next).toBeNull()
const equines = await searchAnimals(asC, {
workspaceId: wC,
query: '',
speciesId: 'equine',
archived: false,
pageSize: 50,
})
expect(equines.rows.map((r) => r.id)).not.toContain(dog.id)
const canines = await searchAnimals(asC, {
workspaceId: wC,
query: '',
speciesId: 'canine',
archived: false,
})
expect(canines.rows.map((r) => r.id)).toEqual([dog.id])
expect(await setAnimalArchived(asC, dog.id, true)).toEqual({ revision: 2 })
const active = await searchAnimals(asC, {
workspaceId: wC,
query: 'chien',
speciesId: null,
archived: false,
})
expect(active.rows).toEqual([])
const archived = await searchAnimals(asC, {
workspaceId: wC,
query: 'chien',
speciesId: null,
archived: true,
})
expect(archived.rows.map((r) => r.id)).toEqual([dog.id])
})
it('nothing of A reaches B: reads empty, writes not_found', async () => {
const clientId = await clientOfA('Client Secret')
const created = await createAnimalRecord(asA, {
workspaceId: wA,
requestId: randomUUID(),
fields: animal('Animal Secret'),
relation: { clientId, relationRole: 'owner', startedOn: null },
})
const relationId = created.relationId as string
expect(await fetchAnimalRecord(asB, created.id)).toBeNull()
expect(await fetchAnimalRecord(asA, randomUUID())).toBeNull()
expect(await fetchAnimalRelations(asB, created.id)).toEqual([])
const search = await searchAnimals(asB, {
workspaceId: wB,
query: 'secret',
speciesId: null,
archived: false,
})
expect(search.rows).toEqual([])
const bAnimal = await createAnimalRecord(asB, {
workspaceId: wB,
requestId: randomUUID(),
fields: animal('Animal de B'),
relation: null,
})
for (const write of [
() =>
updateAnimalRecord(asB, {
animalId: created.id,
expectedRevision: 1,
fields: animal('X'),
}),
() => setAnimalArchived(asB, created.id, true),
() =>
createAnimalClientRelation(asB, {
animalId: bAnimal.id,
clientId,
requestId: randomUUID(),
relationRole: 'owner',
startedOn: null,
}),
() =>
endAnimalClientRelation(asB, {
relationId,
expectedRevision: 1,
endedOn: null,
}),
() =>
updateAnimalClientRelation(asB, {
relationId,
expectedRevision: 1,
startedOn: null,
endedOn: null,
}),
() => voidAnimalClientRelation(asB, { relationId, expectedRevision: 1 }),
() =>
createAnimalRecord(asB, {
workspaceId: wA,
requestId: randomUUID(),
fields: animal('Intrus'),
relation: null,
}),
])
expect(await kindOf(write())).toBe('not_found')
expect(await fetchAnimalRelations(asA, created.id)).toHaveLength(1)
})
it('a relation: duplicate refused, end with and without date, already_ended, dates, conflict', async () => {
const animalId = await animalOfA('Relation Fictive')
const owner = await clientOfA('Propriétaire Fictif')
const keeper = await clientOfA('Détenteur Fictif')
const rel = await createAnimalClientRelation(asA, {
animalId,
clientId: owner,
requestId: randomUUID(),
relationRole: 'owner',
startedOn: '2019-03-01',
})
expect(rel.revision).toBe(1)
expect(
await kindOf(
createAnimalClientRelation(asA, {
animalId,
clientId: owner,
requestId: randomUUID(),
relationRole: 'owner',
startedOn: null,
}),
),
).toBe('duplicate_relation')
const keep = await createAnimalClientRelation(asA, {
animalId,
clientId: keeper,
requestId: randomUUID(),
relationRole: 'keeper',
startedOn: null,
})
expect(
await endAnimalClientRelation(asA, {
relationId: rel.id,
expectedRevision: 1,
endedOn: '2024-05-01',
}),
).toEqual({ revision: 2 })
expect(
await endAnimalClientRelation(asA, {
relationId: keep.id,
expectedRevision: 1,
endedOn: null,
}),
).toEqual({ revision: 2 })
expect(
await kindOf(
endAnimalClientRelation(asA, {
relationId: rel.id,
expectedRevision: 2,
endedOn: null,
}),
),
).toBe('already_ended')
const relations = await fetchAnimalRelations(asA, animalId)
const byId = new Map(relations.map((r) => [r.id, r]))
expect(byId.get(rel.id)).toMatchObject({
ended_on: '2024-05-01',
started_on: '2019-03-01',
})
expect(byId.get(rel.id)?.ended_at).not.toBeNull()
expect(byId.get(keep.id)).toMatchObject({ ended_on: null })
expect(byId.get(keep.id)?.ended_at).not.toBeNull()
expect(
await updateAnimalClientRelation(asA, {
relationId: rel.id,
expectedRevision: 2,
startedOn: null,
endedOn: '2024-06-01',
}),
).toEqual({ revision: 3 })
expect(
(await fetchAnimalRelations(asA, animalId)).find((r) => r.id === rel.id),
).toMatchObject({ started_on: null, ended_on: '2024-06-01', revision: 3 })
expect(
await kindOf(
updateAnimalClientRelation(asA, {
relationId: rel.id,
expectedRevision: 2,
startedOn: null,
endedOn: null,
}),
),
).toBe('conflict')
// A successive relation of the same triple once the first has ended.
expect(
(
await createAnimalClientRelation(asA, {
animalId,
clientId: owner,
requestId: randomUUID(),
relationRole: 'owner',
startedOn: null,
})
).revision,
).toBe(1)
})
it('a voided relation leaves the relations, the current owners and the client animals', async () => {
const owner = await clientOfA('Erreur de Saisie')
const created = await createAnimalRecord(asA, {
workspaceId: wA,
requestId: randomUUID(),
fields: animal('Annulation Fictive'),
relation: { clientId: owner, relationRole: 'owner', startedOn: null },
})
const relationId = created.relationId as string
expect((await listClientAnimals(asA, owner)).rows).toHaveLength(1)
expect(
await voidAnimalClientRelation(asA, { relationId, expectedRevision: 1 }),
).toEqual({ revision: 2 })
expect(await fetchAnimalRelations(asA, created.id)).toEqual([])
const search = await searchAnimals(asA, {
workspaceId: wA,
query: 'annulation fictive',
speciesId: null,
archived: false,
})
expect(search.rows[0]).toMatchObject({
current_owners: [],
current_owner_count: 0,
})
expect((await listClientAnimals(asA, owner)).rows).toEqual([])
// Voided is frozen: no end, no date change, no second void.
expect(
await kindOf(
endAnimalClientRelation(asA, {
relationId,
expectedRevision: 2,
endedOn: null,
}),
),
).toBe('invalid_input')
expect(
await kindOf(
voidAnimalClientRelation(asA, { relationId, expectedRevision: 2 }),
),
).toBe('invalid_input')
})
it('an archived animal refuses its edits and relation writes, then restores', async () => {
const clientId = await clientOfA('Client Archive')
const created = await createAnimalRecord(asA, {
workspaceId: wA,
requestId: randomUUID(),
fields: animal('Archive Fictive'),
relation: { clientId, relationRole: 'keeper', startedOn: null },
})
const relationId = created.relationId as string
expect(await setAnimalArchived(asA, created.id, true)).toEqual({
revision: 2,
})
const other = await clientOfA('Autre Client')
for (const write of [
() =>
updateAnimalRecord(asA, {
animalId: created.id,
expectedRevision: 2,
fields: animal('Renommé'),
}),
() =>
createAnimalClientRelation(asA, {
animalId: created.id,
clientId: other,
requestId: randomUUID(),
relationRole: 'owner',
startedOn: null,
}),
() =>
endAnimalClientRelation(asA, {
relationId,
expectedRevision: 1,
endedOn: null,
}),
() =>
updateAnimalClientRelation(asA, {
relationId,
expectedRevision: 1,
startedOn: '2020-01-01',
endedOn: null,
}),
() => voidAnimalClientRelation(asA, { relationId, expectedRevision: 1 }),
])
expect(await kindOf(write())).toBe('archived')
expect(await fetchAnimalRelations(asA, created.id)).toHaveLength(1)
expect(await setAnimalArchived(asA, created.id, false)).toEqual({
revision: 3,
})
expect(
await updateAnimalRecord(asA, {
animalId: created.id,
expectedRevision: 3,
fields: animal('Restaurée Fictive', { sex: 'female' }),
}),
).toEqual({ revision: 4 })
expect(
await kindOf(
updateAnimalRecord(asA, {
animalId: created.id,
expectedRevision: 3,
fields: animal('Périmée'),
}),
),
).toBe('conflict')
})
})