scdb-lib 1.0.0

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.
Files changed (2) hide show
  1. package/index.js +43 -0
  2. package/package.json +7 -0
package/index.js ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Create a client that talks to the Secure DB HTTP API.
3
+ * @param { { url?: string, apiKey: string } } options - API base URL (default from SECURE_DB_API_URL or http://localhost:3000) and API key
4
+ * @returns { { query: (sql: string, params?: unknown[]) => Promise<Record<string,unknown>[]>, execute: (sql: string, params?: unknown[]) => Promise<{ changes: number, lastInsertRowid: number }> } }
5
+ */
6
+ export function createClient(options) {
7
+ const baseUrl = (options.url || process.env.SECURE_DB_API_URL || 'http://localhost:3000').replace(/\/$/, '');
8
+ const apiKey = options.apiKey || process.env.SECURE_DB_API_KEY;
9
+ if (!apiKey) {
10
+ throw new Error('API key required (options.apiKey or SECURE_DB_API_KEY)');
11
+ }
12
+
13
+ const headers = {
14
+ 'Content-Type': 'application/json',
15
+ Authorization: `Bearer ${apiKey}`,
16
+ };
17
+
18
+ async function request(method, path, body) {
19
+ const res = await fetch(`${baseUrl}${path}`, {
20
+ method,
21
+ headers,
22
+ body: body ? JSON.stringify(body) : undefined,
23
+ });
24
+ const data = await res.json().catch(() => ({}));
25
+ if (!res.ok) {
26
+ const err = new Error(data.error || res.statusText);
27
+ err.status = res.status;
28
+ err.code = data.code;
29
+ throw err;
30
+ }
31
+ return data;
32
+ }
33
+
34
+ return {
35
+ async query(sql, params = []) {
36
+ const { rows } = await request('POST', '/query', { sql, params });
37
+ return rows ?? [];
38
+ },
39
+ async execute(sql, params = []) {
40
+ return request('POST', '/execute', { sql, params });
41
+ },
42
+ };
43
+ }
package/package.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "scdb-lib",
3
+ "version": "1.0.0",
4
+ "main": "index.js",
5
+ "type": "module",
6
+ "dependencies": {}
7
+ }