@ankhorage/db-supabase 0.0.0-stage → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +352 -0
- package/LICENSE +21 -0
- package/README.md +23 -2
- package/dist/adapter.d.ts +3 -0
- package/dist/adapter.d.ts.map +1 -0
- package/dist/adapter.js +170 -0
- package/dist/adapter.js.map +1 -0
- package/dist/admin.d.ts +4 -0
- package/dist/admin.d.ts.map +1 -0
- package/dist/admin.js +145 -0
- package/dist/admin.js.map +1 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +37 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/query.d.ts +4 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/query.js +94 -0
- package/dist/query.js.map +1 -0
- package/dist/realtime.d.ts +10 -0
- package/dist/realtime.d.ts.map +1 -0
- package/dist/realtime.js +74 -0
- package/dist/realtime.js.map +1 -0
- package/dist/types.d.ts +53 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/validation.d.ts +7 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +43 -0
- package/dist/validation.js.map +1 -0
- package/package.json +79 -4
- package/src/adapter.test.ts +171 -0
- package/src/adapter.ts +237 -0
- package/src/admin.test.ts +106 -0
- package/src/admin.ts +204 -0
- package/src/errors.ts +66 -0
- package/src/index.ts +27 -0
- package/src/metadata/repository.json +42 -0
- package/src/query.ts +122 -0
- package/src/realtime.test.ts +174 -0
- package/src/realtime.ts +127 -0
- package/src/types.ts +69 -0
- package/src/validation.ts +57 -0
package/package.json
CHANGED
|
@@ -1,6 +1,81 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ankhorage/db-supabase",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "2.0.1",
|
|
5
|
+
"description": "Supabase database adapter for Ankhorage contracts with CRUD, schema management, and optional realtime support.",
|
|
6
|
+
"homepage": "https://github.com/ankhorage/db-supabase#readme",
|
|
7
|
+
"bugs": {
|
|
8
|
+
"url": "https://github.com/ankhorage/db-supabase/issues"
|
|
9
|
+
},
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"sideEffects": false,
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/ankhorage/db-supabase.git"
|
|
17
|
+
},
|
|
18
|
+
"keywords": [
|
|
19
|
+
"adapter",
|
|
20
|
+
"ankhorage",
|
|
21
|
+
"crud",
|
|
22
|
+
"database",
|
|
23
|
+
"postgres",
|
|
24
|
+
"realtime",
|
|
25
|
+
"supabase",
|
|
26
|
+
"typescript"
|
|
27
|
+
],
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@ankhorage/contracts": "^27.0.1"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@supabase/supabase-js": "^2.117.2"
|
|
33
|
+
},
|
|
34
|
+
"peerDependenciesMeta": {
|
|
35
|
+
"@supabase/supabase-js": {
|
|
36
|
+
"optional": true
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"src",
|
|
42
|
+
"package.json",
|
|
43
|
+
"README.md",
|
|
44
|
+
"CHANGELOG.md",
|
|
45
|
+
"LICENSE"
|
|
46
|
+
],
|
|
47
|
+
"exports": {
|
|
48
|
+
".": {
|
|
49
|
+
"types": "./dist/index.d.ts",
|
|
50
|
+
"import": "./dist/index.js",
|
|
51
|
+
"default": "./dist/index.js"
|
|
52
|
+
},
|
|
53
|
+
"./package.json": "./package.json"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public"
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"build": "rm -rf dist tsconfig.tsbuildinfo && bun x tsc -p tsconfig.json",
|
|
60
|
+
"changeset": "ankhorage-changeset",
|
|
61
|
+
"changeset:status": "ankhorage-changeset status --since=origin/main",
|
|
62
|
+
"docs": "paradox",
|
|
63
|
+
"lint": "ankhorage-eslint . --max-warnings=0",
|
|
64
|
+
"lint:fix": "ankhorage-eslint . --fix --max-warnings=0",
|
|
65
|
+
"format": "ankhorage-prettier --write .",
|
|
66
|
+
"format:check": "ankhorage-prettier --check .",
|
|
67
|
+
"prepack": "bun run build",
|
|
68
|
+
"test": "bun test src",
|
|
69
|
+
"typecheck": "bun x tsc --noEmit -p tsconfig.json",
|
|
70
|
+
"version-packages": "ankhorage-changeset version",
|
|
71
|
+
"knip:check": "ankhorage-knip"
|
|
72
|
+
},
|
|
73
|
+
"devDependencies": {
|
|
74
|
+
"@ankhorage/devtools": "^2.12.14",
|
|
75
|
+
"@ankhorage/paradox": "^0.6.1",
|
|
76
|
+
"@types/bun": "^1.4.5",
|
|
77
|
+
"@types/node": "^26.6.11",
|
|
78
|
+
"typescript": "^6.0.3"
|
|
79
|
+
},
|
|
80
|
+
"packageManager": "bun@1.4.5"
|
|
81
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test';
|
|
2
|
+
|
|
3
|
+
import { createSupabaseDbAdapter } from './adapter.js';
|
|
4
|
+
|
|
5
|
+
interface FetchCall {
|
|
6
|
+
readonly url: string;
|
|
7
|
+
readonly init: RequestInit | undefined;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface PostRecord {
|
|
11
|
+
readonly id: string;
|
|
12
|
+
readonly title: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
test('maps select input to Supabase PostgREST query params', async () => {
|
|
16
|
+
const calls: FetchCall[] = [];
|
|
17
|
+
const adapter = createSupabaseDbAdapter({
|
|
18
|
+
url: 'https://example.supabase.co',
|
|
19
|
+
anonKey: 'anon',
|
|
20
|
+
fetch: (input, init) => {
|
|
21
|
+
calls.push({ url: fetchInputToString(input), init });
|
|
22
|
+
return Promise.resolve(jsonResponse([{ id: 'post-1', title: 'Hello' }]));
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const result = await adapter.select<PostRecord>({
|
|
27
|
+
table: 'posts',
|
|
28
|
+
columns: ['id', 'title'],
|
|
29
|
+
filters: [{ field: 'title', operator: 'startsWith', value: 'Hel' }],
|
|
30
|
+
sort: [{ field: 'title', direction: 'desc' }],
|
|
31
|
+
page: { limit: 10, offset: 5 },
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
expect(result).toEqual({ ok: true, data: [{ id: 'post-1', title: 'Hello' }] });
|
|
35
|
+
expect(calls).toHaveLength(1);
|
|
36
|
+
|
|
37
|
+
const url = new URL(calls[0]?.url ?? 'https://invalid.test');
|
|
38
|
+
expect(url.pathname).toBe('/rest/v1/posts');
|
|
39
|
+
expect(url.searchParams.get('select')).toBe('id,title');
|
|
40
|
+
expect(url.searchParams.get('title')).toBe('like.Hel*');
|
|
41
|
+
expect(url.searchParams.get('order')).toBe('title.desc');
|
|
42
|
+
expect(url.searchParams.get('limit')).toBe('10');
|
|
43
|
+
expect(url.searchParams.get('offset')).toBe('5');
|
|
44
|
+
expect(readHeader(calls[0]?.init, 'apikey')).toBe('anon');
|
|
45
|
+
expect(readHeader(calls[0]?.init, 'Prefer')).toBe('return=representation');
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test('finds records by id', async () => {
|
|
49
|
+
const adapter = createSupabaseDbAdapter({
|
|
50
|
+
url: 'https://example.supabase.co',
|
|
51
|
+
anonKey: 'anon',
|
|
52
|
+
fetch: () => Promise.resolve(jsonResponse([{ id: 'post-1', title: 'Hello' }])),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const result = await adapter.findById<PostRecord>({ table: 'posts', id: 'post-1' });
|
|
56
|
+
|
|
57
|
+
expect(result).toEqual({ ok: true, data: { id: 'post-1', title: 'Hello' } });
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('normalizes empty findById result to null', async () => {
|
|
61
|
+
const adapter = createSupabaseDbAdapter({
|
|
62
|
+
url: 'https://example.supabase.co',
|
|
63
|
+
anonKey: 'anon',
|
|
64
|
+
fetch: () => Promise.resolve(jsonResponse([])),
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const result = await adapter.findById<PostRecord>({ table: 'posts', id: 'missing' });
|
|
68
|
+
|
|
69
|
+
expect(result).toEqual({ ok: true, data: null });
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test('maps insert values to POST with returning representation', async () => {
|
|
73
|
+
const calls: FetchCall[] = [];
|
|
74
|
+
const adapter = createSupabaseDbAdapter({
|
|
75
|
+
url: 'https://example.supabase.co',
|
|
76
|
+
anonKey: 'anon',
|
|
77
|
+
fetch: (input, init) => {
|
|
78
|
+
calls.push({ url: fetchInputToString(input), init });
|
|
79
|
+
return Promise.resolve(jsonResponse([{ id: 'post-1', title: 'Hello' }]));
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
const result = await adapter.insert<PostRecord>({
|
|
84
|
+
table: 'posts',
|
|
85
|
+
values: { id: 'post-1', title: 'Hello' },
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
expect(result.ok).toBe(true);
|
|
89
|
+
expect(calls[0]?.init?.method).toBe('POST');
|
|
90
|
+
expect(calls[0]?.init?.body).toBe(JSON.stringify({ id: 'post-1', title: 'Hello' }));
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test('requires filters for update', async () => {
|
|
94
|
+
const adapter = createSupabaseDbAdapter({
|
|
95
|
+
url: 'https://example.supabase.co',
|
|
96
|
+
anonKey: 'anon',
|
|
97
|
+
fetch: () => Promise.resolve(jsonResponse([])),
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const result = await adapter.update<PostRecord>({
|
|
101
|
+
table: 'posts',
|
|
102
|
+
values: { title: 'Updated' },
|
|
103
|
+
filters: [],
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
expect(result.ok).toBe(false);
|
|
107
|
+
expect(result.ok === false ? result.error.code : '').toBe('validation_error');
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('requires filters for delete', async () => {
|
|
111
|
+
const adapter = createSupabaseDbAdapter({
|
|
112
|
+
url: 'https://example.supabase.co',
|
|
113
|
+
anonKey: 'anon',
|
|
114
|
+
fetch: () => Promise.resolve(jsonResponse([])),
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
const result = await adapter.delete<PostRecord>({ table: 'posts', filters: [] });
|
|
118
|
+
|
|
119
|
+
expect(result.ok).toBe(false);
|
|
120
|
+
expect(result.ok === false ? result.error.code : '').toBe('validation_error');
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test('normalizes provider errors', async () => {
|
|
124
|
+
const adapter = createSupabaseDbAdapter({
|
|
125
|
+
url: 'https://example.supabase.co',
|
|
126
|
+
anonKey: 'anon',
|
|
127
|
+
fetch: () => Promise.resolve(jsonResponse({ message: 'permission denied' }, 403)),
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
const result = await adapter.select<PostRecord>({ table: 'posts' });
|
|
131
|
+
|
|
132
|
+
expect(result.ok).toBe(false);
|
|
133
|
+
expect(result.ok === false ? result.error.code : '').toBe('permission_denied');
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test('exposes realtime capability only when configured with a client', () => {
|
|
137
|
+
const adapter = createSupabaseDbAdapter({
|
|
138
|
+
url: 'https://example.supabase.co',
|
|
139
|
+
anonKey: 'anon',
|
|
140
|
+
realtime: false,
|
|
141
|
+
fetch: () => Promise.resolve(jsonResponse([])),
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
expect(adapter.capabilities.realtime).toBe(false);
|
|
145
|
+
expect('realtime' in adapter).toBe(false);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
function jsonResponse(body: unknown, status = 200): Response {
|
|
149
|
+
return new Response(JSON.stringify(body), {
|
|
150
|
+
status,
|
|
151
|
+
headers: { 'Content-Type': 'application/json' },
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function fetchInputToString(input: RequestInfo | URL): string {
|
|
156
|
+
if (typeof input === 'string') {
|
|
157
|
+
return input;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (input instanceof URL) {
|
|
161
|
+
return input.toString();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return input.url;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function readHeader(init: RequestInit | undefined, name: string): string | null {
|
|
168
|
+
const headers = new Headers(init?.headers);
|
|
169
|
+
|
|
170
|
+
return headers.get(name);
|
|
171
|
+
}
|
package/src/adapter.ts
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
DbAdapter,
|
|
3
|
+
DbDeleteInput,
|
|
4
|
+
DbFilter,
|
|
5
|
+
DbFindByIdInput,
|
|
6
|
+
DbInsertInput,
|
|
7
|
+
DbRecord,
|
|
8
|
+
DbResult,
|
|
9
|
+
DbSelectInput,
|
|
10
|
+
DbUpdateInput,
|
|
11
|
+
} from '@ankhorage/contracts/db';
|
|
12
|
+
|
|
13
|
+
import { createDbError, mapHttpError, mapNetworkError } from './errors.js';
|
|
14
|
+
import { buildMutationUrl, buildSelectUrl } from './query.js';
|
|
15
|
+
import { createRealtimeApi } from './realtime.js';
|
|
16
|
+
import type { SupabaseDbAdapter, SupabaseDbAdapterOptions } from './types.js';
|
|
17
|
+
import { validateFilters, validateKey, validateUrl } from './validation.js';
|
|
18
|
+
|
|
19
|
+
interface NormalizedConfig {
|
|
20
|
+
readonly url: string;
|
|
21
|
+
readonly anonKey: string;
|
|
22
|
+
readonly schema: string;
|
|
23
|
+
readonly fetch: typeof fetch;
|
|
24
|
+
readonly realtime: boolean;
|
|
25
|
+
readonly realtimeClient: SupabaseDbAdapterOptions['realtimeClient'];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type DbFailureResult = Extract<DbResult<unknown>, { readonly ok: false }>;
|
|
29
|
+
interface DbFindByIdSuccessResult<TRecord extends object> {
|
|
30
|
+
readonly ok: true;
|
|
31
|
+
readonly data: TRecord | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function createSupabaseDbAdapter(options: SupabaseDbAdapterOptions): SupabaseDbAdapter {
|
|
35
|
+
const config = normalizeConfig(options);
|
|
36
|
+
const baseAdapter = createBaseAdapter(config);
|
|
37
|
+
if (!config.realtime || config.realtimeClient === undefined) return baseAdapter;
|
|
38
|
+
return {
|
|
39
|
+
...baseAdapter,
|
|
40
|
+
realtime: createRealtimeApi({
|
|
41
|
+
client: config.realtimeClient,
|
|
42
|
+
defaultSchema: config.schema,
|
|
43
|
+
}),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function createBaseAdapter(config: NormalizedConfig): DbAdapter {
|
|
48
|
+
return {
|
|
49
|
+
capabilities: {
|
|
50
|
+
transactions: false,
|
|
51
|
+
returning: true,
|
|
52
|
+
realtime: config.realtime && config.realtimeClient !== undefined,
|
|
53
|
+
},
|
|
54
|
+
select<TRecord extends object = DbRecord>(input: DbSelectInput) {
|
|
55
|
+
return selectRows<TRecord>(config, input);
|
|
56
|
+
},
|
|
57
|
+
findById<TRecord extends object = DbRecord>(input: DbFindByIdInput) {
|
|
58
|
+
return findRowById<TRecord>(config, input);
|
|
59
|
+
},
|
|
60
|
+
insert<TRecord extends object = DbRecord>(input: DbInsertInput<TRecord>) {
|
|
61
|
+
return insertRows<TRecord>(config, input);
|
|
62
|
+
},
|
|
63
|
+
update<TRecord extends object = DbRecord>(input: DbUpdateInput<TRecord>) {
|
|
64
|
+
return updateRows<TRecord>(config, input);
|
|
65
|
+
},
|
|
66
|
+
delete<TRecord extends object = DbRecord>(input: DbDeleteInput) {
|
|
67
|
+
return deleteRows<TRecord>(config, input);
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function deleteRows<TRecord extends object>(
|
|
73
|
+
config: NormalizedConfig,
|
|
74
|
+
input: DbDeleteInput,
|
|
75
|
+
): Promise<DbResult<TRecord[]>> {
|
|
76
|
+
const validationError = validateRequiredFilters(input.filters, 'Delete');
|
|
77
|
+
if (validationError !== null) return Promise.resolve(validationError);
|
|
78
|
+
const url = buildMutationUrl(config.url, input.table, input.filters);
|
|
79
|
+
return requestRows<TRecord>(config, url, { method: 'DELETE' });
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function findRowById<TRecord extends object>(
|
|
83
|
+
config: NormalizedConfig,
|
|
84
|
+
input: DbFindByIdInput,
|
|
85
|
+
): Promise<DbResult<TRecord | null>> {
|
|
86
|
+
const result = await requestRows<TRecord>(
|
|
87
|
+
config,
|
|
88
|
+
buildSelectUrl(config.url, {
|
|
89
|
+
table: input.table,
|
|
90
|
+
columns: input.columns,
|
|
91
|
+
filters: [{ field: input.idField ?? 'id', operator: 'eq', value: input.id }],
|
|
92
|
+
page: { limit: 1 },
|
|
93
|
+
schema: input.schema,
|
|
94
|
+
}),
|
|
95
|
+
{ method: 'GET' },
|
|
96
|
+
);
|
|
97
|
+
if (!result.ok) return result;
|
|
98
|
+
const success: DbFindByIdSuccessResult<TRecord> = {
|
|
99
|
+
ok: true,
|
|
100
|
+
data: result.data[0] ?? null,
|
|
101
|
+
};
|
|
102
|
+
return success;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function insertRows<TRecord extends object>(
|
|
106
|
+
config: NormalizedConfig,
|
|
107
|
+
input: DbInsertInput<TRecord>,
|
|
108
|
+
): Promise<DbResult<TRecord[]>> {
|
|
109
|
+
const url = buildMutationUrl(config.url, input.table, []);
|
|
110
|
+
return requestRows<TRecord>(config, url, {
|
|
111
|
+
method: 'POST',
|
|
112
|
+
body: JSON.stringify(input.values),
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function normalizeConfig(options: SupabaseDbAdapterOptions): NormalizedConfig {
|
|
117
|
+
const fetchImplementation = options.fetch ?? globalThis.fetch;
|
|
118
|
+
if (typeof fetchImplementation !== 'function') {
|
|
119
|
+
throw new TypeError('A fetch implementation is required to use Supabase Database.');
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
url: validateUrl(options.url),
|
|
123
|
+
anonKey: validateKey(options.anonKey, 'Supabase anon key'),
|
|
124
|
+
schema: options.schema ?? 'public',
|
|
125
|
+
fetch: fetchImplementation,
|
|
126
|
+
realtime: options.realtime ?? false,
|
|
127
|
+
realtimeClient: options.realtimeClient,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function requestRows<TRecord extends object>(
|
|
132
|
+
config: NormalizedConfig,
|
|
133
|
+
url: URL,
|
|
134
|
+
init: RequestInit,
|
|
135
|
+
): Promise<DbResult<TRecord[]>> {
|
|
136
|
+
try {
|
|
137
|
+
const response = await config.fetch(url, {
|
|
138
|
+
...init,
|
|
139
|
+
headers: createHeaders(config, init.headers),
|
|
140
|
+
});
|
|
141
|
+
const body = await readJsonBody(response);
|
|
142
|
+
if (!response.ok) return { ok: false, error: mapHttpError(response.status, body) };
|
|
143
|
+
const records = normalizeRecords<TRecord>(body);
|
|
144
|
+
if (records === null) {
|
|
145
|
+
return {
|
|
146
|
+
ok: false,
|
|
147
|
+
error: createDbError(
|
|
148
|
+
'provider_error',
|
|
149
|
+
'Supabase Database returned an invalid records response.',
|
|
150
|
+
body,
|
|
151
|
+
),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
return { ok: true, data: records };
|
|
155
|
+
} catch (error) {
|
|
156
|
+
if (error instanceof TypeError) {
|
|
157
|
+
return { ok: false, error: createDbError('validation_error', error.message, error) };
|
|
158
|
+
}
|
|
159
|
+
return { ok: false, error: mapNetworkError(error) };
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function selectRows<TRecord extends object>(
|
|
164
|
+
config: NormalizedConfig,
|
|
165
|
+
input: DbSelectInput,
|
|
166
|
+
): Promise<DbResult<TRecord[]>> {
|
|
167
|
+
return requestRows<TRecord>(config, buildSelectUrl(config.url, input), { method: 'GET' });
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function updateRows<TRecord extends object>(
|
|
171
|
+
config: NormalizedConfig,
|
|
172
|
+
input: DbUpdateInput<TRecord>,
|
|
173
|
+
): Promise<DbResult<TRecord[]>> {
|
|
174
|
+
const validationError = validateRequiredFilters(input.filters, 'Update');
|
|
175
|
+
if (validationError !== null) return Promise.resolve(validationError);
|
|
176
|
+
const url = buildMutationUrl(config.url, input.table, input.filters);
|
|
177
|
+
return requestRows<TRecord>(config, url, {
|
|
178
|
+
method: 'PATCH',
|
|
179
|
+
body: JSON.stringify(input.values),
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function validateRequiredFilters(
|
|
184
|
+
filters: readonly DbFilter[],
|
|
185
|
+
label: string,
|
|
186
|
+
): DbFailureResult | null {
|
|
187
|
+
try {
|
|
188
|
+
validateFilters(filters, label);
|
|
189
|
+
return null;
|
|
190
|
+
} catch (error) {
|
|
191
|
+
return {
|
|
192
|
+
ok: false,
|
|
193
|
+
error: createDbError(
|
|
194
|
+
'validation_error',
|
|
195
|
+
error instanceof Error ? error.message : `${label} filters are invalid.`,
|
|
196
|
+
error,
|
|
197
|
+
),
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function createHeaders(
|
|
203
|
+
config: NormalizedConfig,
|
|
204
|
+
existingHeaders: HeadersInit | undefined,
|
|
205
|
+
): Headers {
|
|
206
|
+
const headers = new Headers(existingHeaders);
|
|
207
|
+
headers.set('apikey', config.anonKey);
|
|
208
|
+
headers.set('Authorization', `Bearer ${config.anonKey}`);
|
|
209
|
+
headers.set('Accept', 'application/json');
|
|
210
|
+
headers.set('Content-Type', 'application/json');
|
|
211
|
+
headers.set('Prefer', 'return=representation');
|
|
212
|
+
if (config.schema !== 'public') {
|
|
213
|
+
headers.set('Accept-Profile', config.schema);
|
|
214
|
+
headers.set('Content-Profile', config.schema);
|
|
215
|
+
}
|
|
216
|
+
return headers;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function readJsonBody(response: Response): Promise<unknown> {
|
|
220
|
+
const text = await response.text();
|
|
221
|
+
if (text.trim().length === 0) return [];
|
|
222
|
+
try {
|
|
223
|
+
return JSON.parse(text);
|
|
224
|
+
} catch {
|
|
225
|
+
return text;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function normalizeRecords<TRecord extends object>(value: unknown): TRecord[] | null {
|
|
230
|
+
if (Array.isArray(value)) return value.filter(isRecord<TRecord>);
|
|
231
|
+
if (isRecord<TRecord>(value)) return [value];
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function isRecord<TRecord extends object>(value: unknown): value is TRecord {
|
|
236
|
+
return typeof value === 'object' && value !== null;
|
|
237
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test';
|
|
2
|
+
|
|
3
|
+
import { createSupabaseDbAdminAdapter } from './admin.js';
|
|
4
|
+
|
|
5
|
+
test('generates create collection SQL without executing by default', async () => {
|
|
6
|
+
const adapter = createSupabaseDbAdminAdapter({
|
|
7
|
+
url: 'https://example.supabase.co',
|
|
8
|
+
serviceRoleKey: 'service-role',
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
const result = await adapter.createCollection({
|
|
12
|
+
name: 'posts',
|
|
13
|
+
fields: [
|
|
14
|
+
{ name: 'title', type: 'text', required: true },
|
|
15
|
+
{ name: 'like_count', type: 'number', defaultValue: 0 },
|
|
16
|
+
{ name: 'published', type: 'boolean', defaultValue: false },
|
|
17
|
+
],
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
expect(adapter.capabilities).toEqual({
|
|
21
|
+
schemaGeneration: true,
|
|
22
|
+
directExecution: false,
|
|
23
|
+
});
|
|
24
|
+
expect(result.ok).toBe(true);
|
|
25
|
+
expect(result.ok ? result.executed : true).toBe(false);
|
|
26
|
+
expect(result.ok ? result.sql : '').toContain('create table if not exists "public"."posts"');
|
|
27
|
+
expect(result.ok ? result.sql : '').toContain('"id" uuid primary key default gen_random_uuid()');
|
|
28
|
+
expect(result.ok ? result.sql : '').toContain('"title" text not null');
|
|
29
|
+
expect(result.ok ? result.sql : '').toContain('"like_count" double precision default 0');
|
|
30
|
+
expect(result.ok ? result.sql : '').toContain('"published" boolean default false');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('executes generated SQL only when explicitly configured', async () => {
|
|
34
|
+
const executedSql: string[] = [];
|
|
35
|
+
const adapter = createSupabaseDbAdminAdapter({
|
|
36
|
+
url: 'https://example.supabase.co',
|
|
37
|
+
serviceRoleKey: 'service-role',
|
|
38
|
+
execute: true,
|
|
39
|
+
executeSql: (sql) => {
|
|
40
|
+
executedSql.push(sql);
|
|
41
|
+
return Promise.resolve({ ok: true });
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const result = await adapter.createCollection({
|
|
46
|
+
name: 'posts',
|
|
47
|
+
fields: [{ name: 'title', type: 'text' }],
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
expect(adapter.capabilities).toEqual({
|
|
51
|
+
schemaGeneration: true,
|
|
52
|
+
directExecution: true,
|
|
53
|
+
});
|
|
54
|
+
expect(result).toEqual({
|
|
55
|
+
ok: true,
|
|
56
|
+
sql: executedSql[0],
|
|
57
|
+
executed: true,
|
|
58
|
+
});
|
|
59
|
+
expect(executedSql).toHaveLength(1);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test('refuses execution without a service role key', async () => {
|
|
63
|
+
const adapter = createSupabaseDbAdminAdapter({
|
|
64
|
+
url: 'https://example.supabase.co',
|
|
65
|
+
execute: true,
|
|
66
|
+
executeSql: () => Promise.resolve({ ok: true }),
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
const result = await adapter.createCollection({
|
|
70
|
+
name: 'posts',
|
|
71
|
+
fields: [{ name: 'title', type: 'text' }],
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
expect(result.ok).toBe(false);
|
|
75
|
+
expect(result.ok === false ? result.error.code : '').toBe('missing_service_role_key');
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('generates delete collection SQL', () => {
|
|
79
|
+
const adapter = createSupabaseDbAdminAdapter({
|
|
80
|
+
url: 'https://example.supabase.co',
|
|
81
|
+
serviceRoleKey: 'service-role',
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
const result = adapter.generateDeleteCollectionSql({ name: 'posts' });
|
|
85
|
+
|
|
86
|
+
expect(result).toEqual({
|
|
87
|
+
ok: true,
|
|
88
|
+
sql: 'drop table if exists "public"."posts";',
|
|
89
|
+
executed: false,
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test('rejects invalid collection names', () => {
|
|
94
|
+
const adapter = createSupabaseDbAdminAdapter({
|
|
95
|
+
url: 'https://example.supabase.co',
|
|
96
|
+
serviceRoleKey: 'service-role',
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
const result = adapter.generateCreateCollectionSql({
|
|
100
|
+
name: 'invalid-name',
|
|
101
|
+
fields: [{ name: 'title', type: 'text' }],
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
expect(result.ok).toBe(false);
|
|
105
|
+
expect(result.ok === false ? result.error.code : '').toBe('validation_error');
|
|
106
|
+
});
|