feat(supabase): workspaces and clients access layer with closed failures
fetchPersonalWorkspaceId, client search (keyset, one probe row), read by id with explicit columns, create (request id), update (every field), archive, client animals and archive preview, species labels; RecordFailure kinds of contract §9.4 plus session_expired and network; RPC answers checked by Zod. Unit tests and the same functions against real PostgREST on the sandbox.
This commit is contained in:
1 parent
6251051618
commit
a0e069959b
7 files changed
+1136
No files matched your search
@@ -0,0 +1,287 @@
|
||||
import { z } from 'zod'
|
||||
import type { FaunosteoClient } from './client'
|
||||
import type { Database, Enums, Tables } from './database.types'
|
||||
import {
|
||||
failRecord,
|
||||
RecordFailure,
|
||||
UUID_PATTERN,
|
||||
type RecordPage,
|
||||
} from './records'
|
||||
|
||||
/**
|
||||
* Browser side of the clients of a workspace (contract §5.1, §8.2, §9.3):
|
||||
* one read by id under RLS with an explicit column list, the POST searches,
|
||||
* the three write RPCs. Validation of what the user types lives in the app's
|
||||
* form schemas (D-R7); the database rules decide. Every failure is a
|
||||
* RecordFailure of a closed kind.
|
||||
*/
|
||||
|
||||
export type ClientKind = Enums<'client_kind'>
|
||||
export type AnimalRelationRole = Enums<'animal_relation_role'>
|
||||
export type AnimalSex = Enums<'animal_sex'>
|
||||
|
||||
/** Columns the page reads; the derived keys and the request digest stay server-side. */
|
||||
export const CLIENT_COLUMNS =
|
||||
'id, kind, display_name, email, phone, address_line1, address_line2, postal_code, city, country, revision, archived_at, created_at, updated_at'
|
||||
|
||||
export type ClientRecord = Pick<
|
||||
Tables<'clients'>,
|
||||
| 'id'
|
||||
| 'kind'
|
||||
| 'display_name'
|
||||
| 'email'
|
||||
| 'phone'
|
||||
| 'address_line1'
|
||||
| 'address_line2'
|
||||
| 'postal_code'
|
||||
| 'city'
|
||||
| 'country'
|
||||
| 'revision'
|
||||
| 'archived_at'
|
||||
| 'created_at'
|
||||
| 'updated_at'
|
||||
>
|
||||
|
||||
/** The nine fields a client is created or replaced with; an absent value is null, never ''. */
|
||||
export type ClientFields = Pick<
|
||||
ClientRecord,
|
||||
| 'kind'
|
||||
| 'display_name'
|
||||
| 'email'
|
||||
| 'phone'
|
||||
| 'address_line1'
|
||||
| 'address_line2'
|
||||
| 'postal_code'
|
||||
| 'city'
|
||||
| 'country'
|
||||
>
|
||||
|
||||
/** Keyset position in name order: the last row's name_key and id. */
|
||||
export interface NameCursor {
|
||||
nameKey: string
|
||||
id: string
|
||||
}
|
||||
|
||||
const ClientListItemSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
kind: z.enum(['person', 'organization']),
|
||||
display_name: z.string(),
|
||||
city: z.string().nullable(),
|
||||
phone: z.string().nullable(),
|
||||
email: z.string().nullable(),
|
||||
archived_at: z.string().nullable(),
|
||||
name_key: z.string(),
|
||||
current_animal_count: z.number().int(),
|
||||
})
|
||||
export type ClientListItem = z.infer<typeof ClientListItemSchema>
|
||||
|
||||
export interface ClientSearch {
|
||||
workspaceId: string
|
||||
/** Trimmed by the server; 0 to 100 characters. */
|
||||
query: string
|
||||
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_clients` (POST: the term stays out of the URL). */
|
||||
export async function searchClients(
|
||||
client: FaunosteoClient,
|
||||
search: ClientSearch,
|
||||
): Promise<RecordPage<ClientListItem, NameCursor>> {
|
||||
const size = search.pageSize ?? 25
|
||||
const { data, error, status } = await client.rpc('search_clients', {
|
||||
workspace_id: search.workspaceId,
|
||||
query: search.query,
|
||||
archived: search.archived,
|
||||
page_size: size + 1,
|
||||
after_name_key: search.after?.nameKey,
|
||||
after_id: search.after?.id,
|
||||
})
|
||||
if (error) failRecord(error, status)
|
||||
const parsed = z.array(ClientListItemSchema).safeParse(data)
|
||||
if (!parsed.success) throw new RecordFailure('unavailable', parsed.error)
|
||||
const rows = parsed.data.slice(0, size)
|
||||
const last = rows.at(-1)
|
||||
return {
|
||||
rows,
|
||||
next:
|
||||
parsed.data.length > size && last
|
||||
? { nameKey: last.name_key, id: last.id }
|
||||
: null,
|
||||
}
|
||||
}
|
||||
|
||||
/** The client, or null for an unknown id and for an id of another workspace alike. */
|
||||
export async function fetchClientRecord(
|
||||
client: FaunosteoClient,
|
||||
clientId: string,
|
||||
): Promise<ClientRecord | null> {
|
||||
if (!UUID_PATTERN.test(clientId)) return null
|
||||
const { data, error, status } = await client
|
||||
.from('clients')
|
||||
.select(CLIENT_COLUMNS)
|
||||
.eq('id', clientId)
|
||||
.maybeSingle()
|
||||
if (error) failRecord(error, status)
|
||||
return data
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
export interface CreateClientInput {
|
||||
workspaceId: string
|
||||
/** One per creation intent, sent again on a retry: the server answers the first client. */
|
||||
requestId: string
|
||||
fields: ClientFields
|
||||
}
|
||||
|
||||
export async function createClientRecord(
|
||||
client: FaunosteoClient,
|
||||
input: CreateClientInput,
|
||||
): Promise<{ id: string; revision: number }> {
|
||||
const f = input.fields
|
||||
const { data, error, status } = await client.rpc('create_client', {
|
||||
workspace_id: input.workspaceId,
|
||||
create_request_id: input.requestId,
|
||||
kind: f.kind,
|
||||
display_name: f.display_name,
|
||||
email: f.email ?? undefined,
|
||||
phone: f.phone ?? undefined,
|
||||
address_line1: f.address_line1 ?? undefined,
|
||||
address_line2: f.address_line2 ?? undefined,
|
||||
postal_code: f.postal_code ?? undefined,
|
||||
city: f.city ?? undefined,
|
||||
country: f.country ?? undefined,
|
||||
})
|
||||
if (error) failRecord(error, status)
|
||||
return parsed(CreatedSchema, data)
|
||||
}
|
||||
|
||||
type UpdateClientArgs = Database['public']['Functions']['update_client']['Args']
|
||||
|
||||
export interface UpdateClientInput {
|
||||
clientId: string
|
||||
expectedRevision: number
|
||||
fields: ClientFields
|
||||
}
|
||||
|
||||
/** Replaces the nine fields at `expectedRevision`; a stale revision is `conflict`. */
|
||||
export async function updateClientRecord(
|
||||
client: FaunosteoClient,
|
||||
input: UpdateClientInput,
|
||||
): Promise<{ revision: number }> {
|
||||
const f = input.fields
|
||||
// The update RPC has no defaults: every field is sent, null included. The
|
||||
// generator types SQL parameters as non-null, so the keys and value types
|
||||
// are checked against it with null allowed, then handed over.
|
||||
const args = {
|
||||
client_id: input.clientId,
|
||||
expected_revision: input.expectedRevision,
|
||||
kind: f.kind,
|
||||
display_name: f.display_name,
|
||||
email: f.email,
|
||||
phone: f.phone,
|
||||
address_line1: f.address_line1,
|
||||
address_line2: f.address_line2,
|
||||
postal_code: f.postal_code,
|
||||
city: f.city,
|
||||
country: f.country,
|
||||
} satisfies { [K in keyof UpdateClientArgs]: UpdateClientArgs[K] | null }
|
||||
const { data, error, status } = await client.rpc(
|
||||
'update_client',
|
||||
args as UpdateClientArgs,
|
||||
)
|
||||
if (error) failRecord(error, status)
|
||||
return parsed(RevisionSchema, data)
|
||||
}
|
||||
|
||||
export async function setClientArchived(
|
||||
client: FaunosteoClient,
|
||||
clientId: string,
|
||||
archived: boolean,
|
||||
): Promise<{ revision: number }> {
|
||||
const { data, error, status } = await client.rpc('set_client_archived', {
|
||||
client_id: clientId,
|
||||
archived,
|
||||
})
|
||||
if (error) failRecord(error, status)
|
||||
return parsed(RevisionSchema, data)
|
||||
}
|
||||
|
||||
const ArchivePreviewSchema = z.object({
|
||||
count: z.number().int(),
|
||||
animals: z.array(z.object({ id: z.string().uuid(), name: z.string() })),
|
||||
})
|
||||
export type ClientArchivePreview = z.infer<typeof ArchivePreviewSchema>
|
||||
|
||||
/** Active animals for which the client is the only current owner (first 10 by name). */
|
||||
export async function fetchClientArchivePreview(
|
||||
client: FaunosteoClient,
|
||||
clientId: string,
|
||||
): Promise<ClientArchivePreview> {
|
||||
const { data, error, status } = await client.rpc('client_archive_preview', {
|
||||
client_id: clientId,
|
||||
})
|
||||
if (error) failRecord(error, status)
|
||||
return parsed(ArchivePreviewSchema, data)
|
||||
}
|
||||
|
||||
const ClientAnimalSchema = z.object({
|
||||
relation_id: z.string().uuid(),
|
||||
relation_role: z.enum(['owner', 'keeper', 'contact']),
|
||||
started_on: z.string().nullable(),
|
||||
ended_on: z.string().nullable(),
|
||||
is_current: z.boolean(),
|
||||
animal_id: z.string().uuid(),
|
||||
animal_name: z.string(),
|
||||
species_id: z.string(),
|
||||
species_detail: z.string().nullable(),
|
||||
animal_archived_at: z.string().nullable(),
|
||||
sort_key: z.string(),
|
||||
})
|
||||
/** A relation of the client with its animal: read-only view of V1-1.5. */
|
||||
export type ClientAnimalItem = z.infer<typeof ClientAnimalSchema>
|
||||
|
||||
/** Keyset position of `list_client_animals`: the last row's sort_key and relation id. */
|
||||
export interface RelationCursor {
|
||||
sortKey: string
|
||||
relationId: string
|
||||
}
|
||||
|
||||
/** The client's relations, current first then former, each in animal name order. */
|
||||
export async function listClientAnimals(
|
||||
client: FaunosteoClient,
|
||||
clientId: string,
|
||||
options: { pageSize?: number; after?: RelationCursor | null } = {},
|
||||
): Promise<RecordPage<ClientAnimalItem, RelationCursor>> {
|
||||
const size = options.pageSize ?? 50
|
||||
const { data, error, status } = await client.rpc('list_client_animals', {
|
||||
client_id: clientId,
|
||||
page_size: size + 1,
|
||||
after_sort: options.after?.sortKey,
|
||||
after_id: options.after?.relationId,
|
||||
})
|
||||
if (error) failRecord(error, status)
|
||||
const rows = parsed(z.array(ClientAnimalSchema), data)
|
||||
const page = rows.slice(0, size)
|
||||
const last = page.at(-1)
|
||||
return {
|
||||
rows: page,
|
||||
next:
|
||||
rows.length > size && last
|
||||
? { sortKey: last.sort_key, relationId: last.relation_id }
|
||||
: null,
|
||||
}
|
||||
}
|
||||
@@ -89,3 +89,47 @@ export type SheetVisibility = Enums<'sheet_visibility'>
|
||||
export type SheetStatus = Enums<'sheet_status'>
|
||||
/** draft | published | deprecated. */
|
||||
export type SheetVersionStatus = Enums<'sheet_version_status'>
|
||||
export {
|
||||
RECORD_FAILURE_KINDS,
|
||||
RecordFailure,
|
||||
classifyRecordError,
|
||||
type RecordFailureKind,
|
||||
type RecordPage,
|
||||
} from './records'
|
||||
export { fetchPersonalWorkspaceId } from './workspaces'
|
||||
export { fetchSpeciesLabels, type SpeciesLabel } from './species'
|
||||
export {
|
||||
CLIENT_COLUMNS,
|
||||
createClientRecord,
|
||||
fetchClientArchivePreview,
|
||||
fetchClientRecord,
|
||||
listClientAnimals,
|
||||
searchClients,
|
||||
setClientArchived,
|
||||
updateClientRecord,
|
||||
type AnimalRelationRole,
|
||||
type AnimalSex,
|
||||
type ClientAnimalItem,
|
||||
type ClientArchivePreview,
|
||||
type ClientFields,
|
||||
type ClientKind,
|
||||
type ClientListItem,
|
||||
type ClientRecord,
|
||||
type ClientSearch,
|
||||
type CreateClientInput,
|
||||
type NameCursor,
|
||||
type RelationCursor,
|
||||
type UpdateClientInput,
|
||||
} from './clients'
|
||||
export {
|
||||
ANIMAL_FIELD_LIMITS,
|
||||
BIRTH_YEAR_MIN,
|
||||
CLIENT_FIELD_LIMITS,
|
||||
CONTROL_CHARACTERS,
|
||||
COUNTRY_CODE_PATTERN,
|
||||
EMAIL_PATTERN,
|
||||
PHONE_E164_PATTERN,
|
||||
RECORD_DATE_MIN,
|
||||
codePointLength,
|
||||
isCleanText,
|
||||
} from './field-limits'
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* 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
|
||||
* server answers closed codes, never values; this module folds them, the
|
||||
* session and the network into one kind the UI phrases. A foreign id and an
|
||||
* unknown one are the same `not_found`, as the server makes them.
|
||||
*/
|
||||
|
||||
export const RECORD_FAILURE_KINDS = [
|
||||
'not_found',
|
||||
'archived',
|
||||
'conflict',
|
||||
'request_conflict',
|
||||
'limit_reached',
|
||||
'rate_limited',
|
||||
'invalid_input',
|
||||
'session_expired',
|
||||
'network',
|
||||
'unavailable',
|
||||
] as const
|
||||
export type RecordFailureKind = (typeof RECORD_FAILURE_KINDS)[number]
|
||||
|
||||
export class RecordFailure extends Error {
|
||||
readonly kind: RecordFailureKind
|
||||
constructor(kind: RecordFailureKind, cause?: unknown) {
|
||||
super(`record: ${kind}`, { cause })
|
||||
this.name = 'RecordFailure'
|
||||
this.kind = kind
|
||||
}
|
||||
}
|
||||
|
||||
/** Messages the record RPCs raise with SQLSTATE P0001 (contract §9.4). */
|
||||
const RPC_MESSAGE_KINDS: ReadonlySet<string> = new Set([
|
||||
'archived',
|
||||
'conflict',
|
||||
'request_conflict',
|
||||
'limit_reached',
|
||||
'rate_limited',
|
||||
'invalid_input',
|
||||
])
|
||||
|
||||
interface PostgrestLikeError {
|
||||
code?: string | null
|
||||
message?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds a PostgREST answer into a closed kind. `status` is the HTTP status
|
||||
* postgrest-js returns beside the error: 0 when the request never got an
|
||||
* answer, 401 when the JWT is missing or expired (PGRST30x).
|
||||
*/
|
||||
export function classifyRecordError(
|
||||
error: unknown,
|
||||
status?: number,
|
||||
): RecordFailureKind {
|
||||
if (error instanceof RecordFailure) return error.kind
|
||||
if (error instanceof TypeError) return 'network'
|
||||
const e = (error ?? {}) as PostgrestLikeError
|
||||
if (e.code === '42501' && e.message === 'not_found') return 'not_found'
|
||||
if (e.code === 'P0001' && e.message && RPC_MESSAGE_KINDS.has(e.message)) {
|
||||
return e.message as RecordFailureKind
|
||||
}
|
||||
if (status === 401 || e.code?.startsWith('PGRST30')) return 'session_expired'
|
||||
if (status === 0) return 'network'
|
||||
return 'unavailable'
|
||||
}
|
||||
|
||||
/** Throws the closed failure of a PostgREST answer. */
|
||||
export function failRecord(error: unknown, status?: number): never {
|
||||
throw new RecordFailure(classifyRecordError(error, status), error)
|
||||
}
|
||||
|
||||
/** 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
|
||||
|
||||
/** One page of a keyset list; `next` is null on the last page. */
|
||||
export interface RecordPage<Row, Cursor> {
|
||||
rows: Row[]
|
||||
next: Cursor | null
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { FaunosteoClient } from './client'
|
||||
import type { Tables } from './database.types'
|
||||
import { failRecord } from './records'
|
||||
|
||||
export type SpeciesLabel = Pick<Tables<'species'>, 'id' | 'name_fr' | 'name_en'>
|
||||
|
||||
/** The active species with their names, in the reference order (RLS: active rows only). */
|
||||
export async function fetchSpeciesLabels(
|
||||
client: FaunosteoClient,
|
||||
): Promise<SpeciesLabel[]> {
|
||||
const { data, error, status } = await client
|
||||
.from('species')
|
||||
.select('id, name_fr, name_en')
|
||||
.order('sort_order')
|
||||
if (error) failRecord(error, status)
|
||||
return data ?? []
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { FaunosteoClient } from './client'
|
||||
import { failRecord } from './records'
|
||||
|
||||
/**
|
||||
* The signed-in account's personal workspace (contract §4, M1). It is
|
||||
* created by the server in the sign-up transaction, never by the browser;
|
||||
* RLS returns it only to its member with an active profile and a confirmed
|
||||
* email, so null means "not readable now", not "create one". Its id is a
|
||||
* context for the RPCs, which check the caller's rights again themselves.
|
||||
*/
|
||||
export async function fetchPersonalWorkspaceId(
|
||||
client: FaunosteoClient,
|
||||
userId: string,
|
||||
): Promise<string | null> {
|
||||
const { data, error, status } = await client
|
||||
.from('workspaces')
|
||||
.select('id')
|
||||
.eq('personal_user_id', userId)
|
||||
.maybeSingle()
|
||||
if (error) failRecord(error, status)
|
||||
return data?.id ?? null
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
import {
|
||||
RecordFailure,
|
||||
classifyRecordError,
|
||||
createClientRecord,
|
||||
fetchClientArchivePreview,
|
||||
fetchClientRecord,
|
||||
fetchPersonalWorkspaceId,
|
||||
listClientAnimals,
|
||||
searchClients,
|
||||
setClientArchived,
|
||||
updateClientRecord,
|
||||
type ClientFields,
|
||||
type FaunosteoClient,
|
||||
} from '../src'
|
||||
|
||||
/**
|
||||
* Call shapes and closed failure kinds of the workspaces and clients access
|
||||
* layer. The argument names are checked by the compiler against the generated
|
||||
* types; the RPC bodies by supabase/tests/013_clients.sql and 014; the same
|
||||
* functions run against real PostgREST in tests/sandbox/clients-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 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),
|
||||
maybeSingle: async () => 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 }
|
||||
}
|
||||
|
||||
const WS = '11111111-1111-4111-8111-111111111111'
|
||||
const ID = '22222222-2222-4222-8222-222222222222'
|
||||
const REQUEST = '33333333-3333-4333-8333-333333333333'
|
||||
|
||||
const fields: ClientFields = {
|
||||
kind: 'person',
|
||||
display_name: 'Marie Dupont',
|
||||
email: null,
|
||||
phone: '+33612345678',
|
||||
address_line1: null,
|
||||
address_line2: null,
|
||||
postal_code: null,
|
||||
city: 'Lyon',
|
||||
country: null,
|
||||
}
|
||||
|
||||
function listRow(i: number) {
|
||||
return {
|
||||
id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
|
||||
kind: 'person',
|
||||
display_name: `Client ${i}`,
|
||||
city: null,
|
||||
phone: null,
|
||||
email: null,
|
||||
archived_at: null,
|
||||
name_key: `client ${String(i).padStart(3, '0')}`,
|
||||
current_animal_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
async function kindOf(promise: Promise<unknown>) {
|
||||
try {
|
||||
await promise
|
||||
return 'no failure'
|
||||
} catch (error) {
|
||||
return error instanceof RecordFailure ? error.kind : 'not a RecordFailure'
|
||||
}
|
||||
}
|
||||
|
||||
describe('classifyRecordError', () => {
|
||||
it.each([
|
||||
[{ code: '42501', message: 'not_found' }, 403, 'not_found'],
|
||||
[{ code: 'P0001', message: 'archived' }, 400, 'archived'],
|
||||
[{ code: 'P0001', message: 'conflict' }, 400, 'conflict'],
|
||||
[{ code: 'P0001', message: 'request_conflict' }, 400, 'request_conflict'],
|
||||
[{ code: 'P0001', message: 'limit_reached' }, 400, 'limit_reached'],
|
||||
[{ code: 'P0001', message: 'rate_limited' }, 400, 'rate_limited'],
|
||||
[{ code: 'P0001', message: 'invalid_input' }, 400, 'invalid_input'],
|
||||
[{ code: 'P0001', message: 'something else' }, 400, 'unavailable'],
|
||||
[
|
||||
{ code: '42501', message: 'permission denied for table clients' },
|
||||
403,
|
||||
'unavailable',
|
||||
],
|
||||
[{ code: 'PGRST301', message: 'JWT expired' }, 401, 'session_expired'],
|
||||
[{ code: '', message: 'anything' }, 401, 'session_expired'],
|
||||
[{ code: '', message: 'TypeError: Failed to fetch' }, 0, 'network'],
|
||||
[
|
||||
{
|
||||
code: '57014',
|
||||
message: 'canceling statement due to statement timeout',
|
||||
},
|
||||
500,
|
||||
'unavailable',
|
||||
],
|
||||
])('%o with HTTP %i is %s', (error, status, kind) => {
|
||||
expect(classifyRecordError(error, status)).toBe(kind)
|
||||
})
|
||||
|
||||
it('reads a thrown TypeError as the network', () => {
|
||||
expect(classifyRecordError(new TypeError('Failed to fetch'))).toBe(
|
||||
'network',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fetchPersonalWorkspaceId', () => {
|
||||
it('reads the id of the workspace whose personal user is the caller', async () => {
|
||||
const { client, query } = stubClient({ select: { data: { id: WS } } })
|
||||
expect(await fetchPersonalWorkspaceId(client, 'user-1')).toBe(WS)
|
||||
expect(query).toEqual({
|
||||
table: 'workspaces',
|
||||
select: 'id',
|
||||
'eq:personal_user_id': 'user-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('answers null when RLS returns no row, and a closed kind on failure', async () => {
|
||||
expect(
|
||||
await fetchPersonalWorkspaceId(stubClient().client, 'user-1'),
|
||||
).toBeNull()
|
||||
const failing = stubClient({
|
||||
select: { error: { code: '', message: 'FetchError' }, status: 0 },
|
||||
})
|
||||
expect(
|
||||
await kindOf(fetchPersonalWorkspaceId(failing.client, 'user-1')),
|
||||
).toBe('network')
|
||||
})
|
||||
})
|
||||
|
||||
describe('searchClients', () => {
|
||||
it('posts the term, asks one row more than the page and leaves the cursor out on page one', async () => {
|
||||
const { client, rpcCalls } = stubClient({ rpc: { data: [listRow(1)] } })
|
||||
const page = await searchClients(client, {
|
||||
workspaceId: WS,
|
||||
query: 'marie',
|
||||
archived: false,
|
||||
})
|
||||
expect(rpcCalls).toEqual([
|
||||
[
|
||||
'search_clients',
|
||||
{
|
||||
workspace_id: WS,
|
||||
query: 'marie',
|
||||
archived: false,
|
||||
page_size: 26,
|
||||
after_name_key: undefined,
|
||||
after_id: undefined,
|
||||
},
|
||||
],
|
||||
])
|
||||
expect(page).toEqual({ rows: [listRow(1)], next: null })
|
||||
})
|
||||
|
||||
it('keeps 25 rows and turns the 26th into a next cursor at the 25th', async () => {
|
||||
const rows = Array.from({ length: 26 }, (_, i) => listRow(i + 1))
|
||||
const { client, rpcCalls } = stubClient({ rpc: { data: rows } })
|
||||
const page = await searchClients(client, {
|
||||
workspaceId: WS,
|
||||
query: '',
|
||||
archived: true,
|
||||
after: { nameKey: 'client 000', id: ID },
|
||||
})
|
||||
expect(page.rows).toHaveLength(25)
|
||||
expect(page.next).toEqual({ nameKey: rows[24].name_key, id: rows[24].id })
|
||||
expect(rpcCalls[0][1]).toMatchObject({
|
||||
after_name_key: 'client 000',
|
||||
after_id: ID,
|
||||
archived: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses an answer of another shape as unavailable', async () => {
|
||||
const { client } = stubClient({ rpc: { data: [{ id: 'x' }] } })
|
||||
expect(
|
||||
await kindOf(
|
||||
searchClients(client, { workspaceId: WS, query: '', archived: false }),
|
||||
),
|
||||
).toBe('unavailable')
|
||||
})
|
||||
})
|
||||
|
||||
describe('fetchClientRecord', () => {
|
||||
it('reads one client by id with the explicit column list', async () => {
|
||||
const { client, query } = stubClient({ select: { data: { id: ID } } })
|
||||
expect(await fetchClientRecord(client, ID)).toEqual({ id: ID })
|
||||
expect(query.table).toBe('clients')
|
||||
expect(query['eq:id']).toBe(ID)
|
||||
expect(String(query.select)).not.toContain('*')
|
||||
expect(String(query.select)).not.toContain('create_request_digest')
|
||||
})
|
||||
|
||||
it('answers null for an id that is not a uuid, without a request', async () => {
|
||||
const { client, query } = stubClient()
|
||||
expect(await fetchClientRecord(client, 'not-a-uuid')).toBeNull()
|
||||
expect(query.table).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('client writes', () => {
|
||||
it('creates with the request id and leaves absent optionals to their defaults', async () => {
|
||||
const { client, rpcCalls } = stubClient({
|
||||
rpc: { data: { id: ID, revision: 1 } },
|
||||
})
|
||||
expect(
|
||||
await createClientRecord(client, {
|
||||
workspaceId: WS,
|
||||
requestId: REQUEST,
|
||||
fields,
|
||||
}),
|
||||
).toEqual({
|
||||
id: ID,
|
||||
revision: 1,
|
||||
})
|
||||
expect(rpcCalls[0]).toEqual([
|
||||
'create_client',
|
||||
{
|
||||
workspace_id: WS,
|
||||
create_request_id: REQUEST,
|
||||
kind: 'person',
|
||||
display_name: 'Marie Dupont',
|
||||
email: undefined,
|
||||
phone: '+33612345678',
|
||||
address_line1: undefined,
|
||||
address_line2: undefined,
|
||||
postal_code: undefined,
|
||||
city: 'Lyon',
|
||||
country: undefined,
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('updates with every field, null included, at the expected revision', async () => {
|
||||
const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 3 } } })
|
||||
expect(
|
||||
await updateClientRecord(client, {
|
||||
clientId: ID,
|
||||
expectedRevision: 2,
|
||||
fields,
|
||||
}),
|
||||
).toEqual({ revision: 3 })
|
||||
expect(rpcCalls[0]).toEqual([
|
||||
'update_client',
|
||||
{ client_id: ID, expected_revision: 2, ...fields },
|
||||
])
|
||||
})
|
||||
|
||||
it('archives and restores through set_client_archived', async () => {
|
||||
const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } })
|
||||
expect(await setClientArchived(client, ID, true)).toEqual({ revision: 2 })
|
||||
expect(rpcCalls[0]).toEqual([
|
||||
'set_client_archived',
|
||||
{ client_id: ID, archived: true },
|
||||
])
|
||||
})
|
||||
|
||||
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(
|
||||
updateClientRecord(client, {
|
||||
clientId: ID,
|
||||
expectedRevision: 1,
|
||||
fields,
|
||||
}),
|
||||
),
|
||||
).toBe(message)
|
||||
})
|
||||
|
||||
it('an unknown or foreign id is not_found', async () => {
|
||||
const { client } = stubClient({
|
||||
rpc: { error: { code: '42501', message: 'not_found' }, status: 403 },
|
||||
})
|
||||
expect(await kindOf(setClientArchived(client, ID, true))).toBe('not_found')
|
||||
})
|
||||
})
|
||||
|
||||
describe('client animals and archive preview', () => {
|
||||
it('lists 50 relations per page by default with a cursor on sort_key and relation id', async () => {
|
||||
const row = (i: number) => ({
|
||||
relation_id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
|
||||
relation_role: 'owner',
|
||||
started_on: null,
|
||||
ended_on: null,
|
||||
is_current: true,
|
||||
relation_revision: 1,
|
||||
animal_id: ID,
|
||||
animal_name: `Animal ${i}`,
|
||||
species_id: 'equine',
|
||||
species_detail: null,
|
||||
sex: 'female',
|
||||
breed: null,
|
||||
birth_year: null,
|
||||
animal_archived_at: null,
|
||||
sort_key: `0animal ${String(i).padStart(3, '0')}`,
|
||||
})
|
||||
const rows = Array.from({ length: 51 }, (_, i) => row(i + 1))
|
||||
const { client, rpcCalls } = stubClient({ rpc: { data: rows } })
|
||||
const page = await listClientAnimals(client, ID)
|
||||
expect(rpcCalls[0]).toEqual([
|
||||
'list_client_animals',
|
||||
{
|
||||
client_id: ID,
|
||||
page_size: 51,
|
||||
after_sort: undefined,
|
||||
after_id: undefined,
|
||||
},
|
||||
])
|
||||
expect(page.rows).toHaveLength(50)
|
||||
expect(page.next).toEqual({
|
||||
sortKey: rows[49].sort_key,
|
||||
relationId: rows[49].relation_id,
|
||||
})
|
||||
})
|
||||
|
||||
it('reads the archive preview', async () => {
|
||||
const preview = { count: 1, animals: [{ id: ID, name: 'Éclair' }] }
|
||||
const { client, rpcCalls } = stubClient({ rpc: { data: preview } })
|
||||
expect(await fetchClientArchivePreview(client, ID)).toEqual(preview)
|
||||
expect(rpcCalls[0]).toEqual(['client_archive_preview', { client_id: ID }])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,338 @@
|
||||
/**
|
||||
* The V1-1.5 access layer (src/workspaces.ts, src/clients.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
|
||||
* keyset pages and every closed failure kind come from the real server, not
|
||||
* from a stub. One base URL is mapped onto the sandbox services, as Kong does.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import {
|
||||
RecordFailure,
|
||||
createClientRecord,
|
||||
fetchClientArchivePreview,
|
||||
fetchClientRecord,
|
||||
fetchPersonalWorkspaceId,
|
||||
listClientAnimals,
|
||||
searchClients,
|
||||
setClientArchived,
|
||||
updateClientRecord,
|
||||
type ClientFields,
|
||||
type Database,
|
||||
type FaunosteoClient,
|
||||
} from '../../src'
|
||||
import { PASSWORD, confirmedAccount, sql, stack, type Account } from './stack'
|
||||
|
||||
const BASE = 'http://sandbox.faunosteo.invalid'
|
||||
|
||||
/** The browser client of the app, its requests replayed on the sandbox ports. */
|
||||
function browserClient(fetchImpl: typeof fetch = fetch): 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 fetchImpl(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 person = (
|
||||
displayName: string,
|
||||
patch: Partial<ClientFields> = {},
|
||||
): ClientFields => ({
|
||||
kind: 'person',
|
||||
display_name: displayName,
|
||||
email: null,
|
||||
phone: null,
|
||||
address_line1: null,
|
||||
address_line2: null,
|
||||
postal_code: null,
|
||||
city: null,
|
||||
country: null,
|
||||
...patch,
|
||||
})
|
||||
|
||||
describe('workspaces and clients access layer on the sandbox', () => {
|
||||
let a: Account
|
||||
let b: Account
|
||||
let asA: FaunosteoClient
|
||||
let asB: FaunosteoClient
|
||||
let wA: string
|
||||
|
||||
beforeAll(async () => {
|
||||
a = await confirmedAccount('acc-a')
|
||||
b = await confirmedAccount('acc-b')
|
||||
asA = await signedIn(a)
|
||||
asB = await signedIn(b)
|
||||
wA = (await fetchPersonalWorkspaceId(asA, a.id)) as string
|
||||
})
|
||||
|
||||
it('finds the personal workspace of the caller only', async () => {
|
||||
expect(wA).toBe(
|
||||
await sql(
|
||||
`select id from public.workspaces where personal_user_id = '${a.id}'`,
|
||||
),
|
||||
)
|
||||
expect(await fetchPersonalWorkspaceId(asB, a.id)).toBeNull()
|
||||
})
|
||||
|
||||
it('creates idempotently, refuses a divergent replay, reads the explicit columns', async () => {
|
||||
const requestId = randomUUID()
|
||||
const fields = person('Marie Dupont', {
|
||||
email: 'marie@exemple.test',
|
||||
phone: '+33612345678',
|
||||
city: 'Lyon',
|
||||
country: 'FR',
|
||||
})
|
||||
const first = await createClientRecord(asA, {
|
||||
workspaceId: wA,
|
||||
requestId,
|
||||
fields,
|
||||
})
|
||||
const replay = await createClientRecord(asA, {
|
||||
workspaceId: wA,
|
||||
requestId,
|
||||
fields,
|
||||
})
|
||||
expect(replay).toEqual(first)
|
||||
expect(
|
||||
await kindOf(
|
||||
createClientRecord(asA, {
|
||||
workspaceId: wA,
|
||||
requestId,
|
||||
fields: person('Marie Durand'),
|
||||
}),
|
||||
),
|
||||
).toBe('request_conflict')
|
||||
const record = await fetchClientRecord(asA, first.id)
|
||||
expect(Object.keys(record ?? {}).sort()).toEqual(
|
||||
[
|
||||
'address_line1',
|
||||
'address_line2',
|
||||
'archived_at',
|
||||
'city',
|
||||
'country',
|
||||
'created_at',
|
||||
'display_name',
|
||||
'email',
|
||||
'id',
|
||||
'kind',
|
||||
'phone',
|
||||
'postal_code',
|
||||
'revision',
|
||||
'updated_at',
|
||||
].sort(),
|
||||
)
|
||||
expect(record).toMatchObject({ ...fields, revision: 1, archived_at: null })
|
||||
})
|
||||
|
||||
it('updates at the revision, clears a field with null, refuses a stale revision', async () => {
|
||||
const { id } = await createClientRecord(asA, {
|
||||
workspaceId: wA,
|
||||
requestId: randomUUID(),
|
||||
fields: person('Paul Martin', { city: 'Annecy' }),
|
||||
})
|
||||
expect(
|
||||
await updateClientRecord(asA, {
|
||||
clientId: id,
|
||||
expectedRevision: 1,
|
||||
fields: person('Paul Martin', { city: null, phone: '+41791234567' }),
|
||||
}),
|
||||
).toEqual({ revision: 2 })
|
||||
expect(await fetchClientRecord(asA, id)).toMatchObject({
|
||||
city: null,
|
||||
phone: '+41791234567',
|
||||
revision: 2,
|
||||
})
|
||||
expect(
|
||||
await kindOf(
|
||||
updateClientRecord(asA, {
|
||||
clientId: id,
|
||||
expectedRevision: 1,
|
||||
fields: person('X'),
|
||||
}),
|
||||
),
|
||||
).toBe('conflict')
|
||||
expect(
|
||||
await kindOf(
|
||||
updateClientRecord(asA, {
|
||||
clientId: id,
|
||||
expectedRevision: 2,
|
||||
fields: person(''),
|
||||
}),
|
||||
),
|
||||
).toBe('invalid_input')
|
||||
})
|
||||
|
||||
it('archives, refuses edits while archived, restores', async () => {
|
||||
const { id } = await createClientRecord(asA, {
|
||||
workspaceId: wA,
|
||||
requestId: randomUUID(),
|
||||
fields: person('Zoé Bernard'),
|
||||
})
|
||||
expect(await setClientArchived(asA, id, true)).toEqual({ revision: 2 })
|
||||
expect(
|
||||
await kindOf(
|
||||
updateClientRecord(asA, {
|
||||
clientId: id,
|
||||
expectedRevision: 2,
|
||||
fields: person('Zoé'),
|
||||
}),
|
||||
),
|
||||
).toBe('archived')
|
||||
const archived = await searchClients(asA, {
|
||||
workspaceId: wA,
|
||||
query: 'zoe',
|
||||
archived: true,
|
||||
})
|
||||
expect(archived.rows.map((r) => r.id)).toEqual([id])
|
||||
expect(await setClientArchived(asA, id, false)).toEqual({ revision: 3 })
|
||||
})
|
||||
|
||||
it('pages 25 by 25 in name order without gap or repeat', async () => {
|
||||
const c = await confirmedAccount('acc-page')
|
||||
const asC = await signedIn(c)
|
||||
const wC = (await fetchPersonalWorkspaceId(asC, c.id)) as string
|
||||
for (let i = 1; i <= 30; i++) {
|
||||
await createClientRecord(asC, {
|
||||
workspaceId: wC,
|
||||
requestId: randomUUID(),
|
||||
fields: person(`Client ${String(i).padStart(2, '0')}`),
|
||||
})
|
||||
}
|
||||
const one = await searchClients(asC, {
|
||||
workspaceId: wC,
|
||||
query: '',
|
||||
archived: false,
|
||||
})
|
||||
expect(one.rows).toHaveLength(25)
|
||||
expect(one.next).not.toBeNull()
|
||||
const two = await searchClients(asC, {
|
||||
workspaceId: wC,
|
||||
query: '',
|
||||
archived: false,
|
||||
after: one.next,
|
||||
})
|
||||
expect(two.rows.map((r) => r.display_name)).toEqual([
|
||||
'Client 26',
|
||||
'Client 27',
|
||||
'Client 28',
|
||||
'Client 29',
|
||||
'Client 30',
|
||||
])
|
||||
expect(two.next).toBeNull()
|
||||
const ids = new Set([...one.rows, ...two.rows].map((r) => r.id))
|
||||
expect(ids.size).toBe(30)
|
||||
})
|
||||
|
||||
it('lists the client animals and the archive preview from the real RPCs', async () => {
|
||||
const { id } = await createClientRecord(asA, {
|
||||
workspaceId: wA,
|
||||
requestId: randomUUID(),
|
||||
fields: person('Écurie du Lac', { kind: 'organization' }),
|
||||
})
|
||||
const created = await asA.rpc('create_animal', {
|
||||
workspace_id: wA,
|
||||
create_request_id: randomUUID(),
|
||||
name: 'Éclair',
|
||||
species_id: 'equine',
|
||||
sex: 'male',
|
||||
client_id: id,
|
||||
relation_role: 'owner',
|
||||
})
|
||||
expect(created.error).toBeNull()
|
||||
const page = await listClientAnimals(asA, id)
|
||||
expect(page.rows).toMatchObject([
|
||||
{ animal_name: 'Éclair', relation_role: 'owner', is_current: true },
|
||||
])
|
||||
expect(page.next).toBeNull()
|
||||
expect(await fetchClientArchivePreview(asA, id)).toMatchObject({
|
||||
count: 1,
|
||||
animals: [{ name: 'Éclair' }],
|
||||
})
|
||||
const listed = await searchClients(asA, {
|
||||
workspaceId: wA,
|
||||
query: 'ecurie',
|
||||
archived: false,
|
||||
})
|
||||
expect(listed.rows).toMatchObject([{ id, current_animal_count: 1 }])
|
||||
})
|
||||
|
||||
it('gives B nothing of A, with the same not_found as an unknown id', async () => {
|
||||
const { id } = await createClientRecord(asA, {
|
||||
workspaceId: wA,
|
||||
requestId: randomUUID(),
|
||||
fields: person('Secret Client'),
|
||||
})
|
||||
expect(await fetchClientRecord(asB, id)).toBeNull()
|
||||
expect(
|
||||
(
|
||||
await searchClients(asB, {
|
||||
workspaceId: wA,
|
||||
query: '',
|
||||
archived: false,
|
||||
})
|
||||
).rows,
|
||||
).toEqual([])
|
||||
expect((await listClientAnimals(asB, id)).rows).toEqual([])
|
||||
expect(await fetchClientArchivePreview(asB, id)).toEqual({
|
||||
count: 0,
|
||||
animals: [],
|
||||
})
|
||||
expect(await kindOf(setClientArchived(asB, id, true))).toBe('not_found')
|
||||
expect(await kindOf(setClientArchived(asB, randomUUID(), true))).toBe(
|
||||
'not_found',
|
||||
)
|
||||
expect(
|
||||
await kindOf(
|
||||
createClientRecord(asB, {
|
||||
workspaceId: wA,
|
||||
requestId: randomUUID(),
|
||||
fields: person('X'),
|
||||
}),
|
||||
),
|
||||
).toBe('not_found')
|
||||
})
|
||||
|
||||
it('reads no session as session_expired and an unreachable server as network', async () => {
|
||||
expect(
|
||||
await kindOf(
|
||||
searchClients(browserClient(), {
|
||||
workspaceId: wA,
|
||||
query: '',
|
||||
archived: false,
|
||||
}),
|
||||
),
|
||||
).toBe('session_expired')
|
||||
const offline = browserClient(async () => {
|
||||
throw new TypeError('fetch failed')
|
||||
})
|
||||
expect(
|
||||
await kindOf(
|
||||
searchClients(offline, { workspaceId: wA, query: '', archived: false }),
|
||||
),
|
||||
).toBe('network')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user