@form-engine-ts/storage-postgres 1.1.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.
- package/LICENSE +21 -0
- package/README.md +30 -0
- package/dist/index.cjs +203 -0
- package/dist/index.d.cts +16 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +178 -0
- package/package.json +62 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nitta-a
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# @form-engine-ts/storage-postgres
|
|
2
|
+
|
|
3
|
+
PostgreSQL implementation of the complete form-engine-ts storage contract using an injected node-postgres-compatible query client.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @form-engine-ts/core @form-engine-ts/storage-postgres pg
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick start
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { Pool } from "pg";
|
|
15
|
+
import { createPostgresStorage } from "@form-engine-ts/storage-postgres";
|
|
16
|
+
|
|
17
|
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
|
18
|
+
const storage = createPostgresStorage({ client: pool, autoMigrate: true });
|
|
19
|
+
|
|
20
|
+
await storage.saveSchema(schema);
|
|
21
|
+
await storage.saveSubmission(submission);
|
|
22
|
+
const submissions = await storage.listSubmissions(schema.id, schema.version, {
|
|
23
|
+
since: "2026-01-01T00:00:00.000Z",
|
|
24
|
+
until: "2026-01-31T23:59:59.999Z"
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`client` may be a `Pool`, `Client`, or a wrapper exposing the same `query(text, values)` shape. The caller owns connections and transactions. `autoMigrate` defaults to `false`; when enabled, the adapter lazily runs idempotent `CREATE TABLE/INDEX IF NOT EXISTS` statements once before its first operation. Use a migration framework for production schema evolution.
|
|
29
|
+
|
|
30
|
+
Schemas use a `(form_id, form_version)` primary key and JSONB payload. Responses use their globally unique ID as the primary key, retain searchable form/version/locale/timestamp columns, and store the complete submission as JSONB. Custom table names must be safe SQL identifiers. Range boundaries are inclusive and results are ordered by submission time and then ID. Schema deletion never cascades to responses; `clearResponses(formId)` removes every version of one form, while `clear()` deletes rows only from the configured tables.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
createPostgresStorage: () => createPostgresStorage
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(index_exports);
|
|
26
|
+
var import_core = require("@form-engine-ts/core");
|
|
27
|
+
function isRecord(value) {
|
|
28
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
29
|
+
}
|
|
30
|
+
function isFormValue(value) {
|
|
31
|
+
return value === void 0 || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
32
|
+
}
|
|
33
|
+
function cloneJson(value) {
|
|
34
|
+
return JSON.parse(JSON.stringify(value));
|
|
35
|
+
}
|
|
36
|
+
function parseJson(value, location) {
|
|
37
|
+
if (typeof value !== "string") return cloneJson(value);
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(value);
|
|
40
|
+
} catch (cause) {
|
|
41
|
+
throw new Error(`Postgres JSON at ${location} is invalid.`, { cause });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function parseSubmission(value, location) {
|
|
45
|
+
const parsed = parseJson(value, location);
|
|
46
|
+
if (!isRecord(parsed) || typeof parsed.id !== "string" || typeof parsed.formId !== "string" || !Number.isInteger(parsed.formVersion) || typeof parsed.locale !== "string" || typeof parsed.submittedAt !== "string" || !isRecord(parsed.values) || !Object.values(parsed.values).every(isFormValue)) {
|
|
47
|
+
throw new Error(`Postgres submission at ${location} is invalid.`);
|
|
48
|
+
}
|
|
49
|
+
return cloneJson(parsed);
|
|
50
|
+
}
|
|
51
|
+
function parseSchemaRow(value, index) {
|
|
52
|
+
if (!isRecord(value)) throw new Error(`Postgres schema row ${index} is invalid.`);
|
|
53
|
+
const row = value;
|
|
54
|
+
const schema = parseJson(row.schema_json, `schema row ${index}`);
|
|
55
|
+
try {
|
|
56
|
+
(0, import_core.assertValidFormSchema)(schema);
|
|
57
|
+
} catch (cause) {
|
|
58
|
+
throw new Error(`Postgres schema row ${index} is invalid.`, { cause });
|
|
59
|
+
}
|
|
60
|
+
if (row.form_id !== schema.id || row.form_version !== schema.version) {
|
|
61
|
+
throw new Error(`Postgres schema row ${index} has inconsistent metadata.`);
|
|
62
|
+
}
|
|
63
|
+
return cloneJson(schema);
|
|
64
|
+
}
|
|
65
|
+
function parseSubmissionRow(value, index) {
|
|
66
|
+
if (!isRecord(value)) throw new Error(`Postgres submission row ${index} is invalid.`);
|
|
67
|
+
const row = value;
|
|
68
|
+
const submission = parseSubmission(row.submission_json, `submission row ${index}`);
|
|
69
|
+
const timestamp = row.submitted_at instanceof Date ? row.submitted_at.toISOString() : row.submitted_at;
|
|
70
|
+
if (row.response_id !== submission.id || row.form_id !== submission.formId || row.form_version !== submission.formVersion || row.locale !== submission.locale || typeof timestamp !== "string" || Date.parse(timestamp) !== Date.parse(submission.submittedAt)) {
|
|
71
|
+
throw new Error(`Postgres submission row ${index} has inconsistent metadata.`);
|
|
72
|
+
}
|
|
73
|
+
return submission;
|
|
74
|
+
}
|
|
75
|
+
function identifier(value, fallback, optionName) {
|
|
76
|
+
const name = value ?? fallback;
|
|
77
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
78
|
+
throw new TypeError(`${optionName} must be a safe SQL identifier.`);
|
|
79
|
+
}
|
|
80
|
+
return `"${name}"`;
|
|
81
|
+
}
|
|
82
|
+
function createPostgresStorage(options) {
|
|
83
|
+
if (options?.client === void 0 || typeof options.client.query !== "function") {
|
|
84
|
+
throw new TypeError("client with a query function is required.");
|
|
85
|
+
}
|
|
86
|
+
const schemasTable = identifier(options.schemasTable, "form_schemas", "schemasTable");
|
|
87
|
+
const responsesTable = identifier(options.responsesTable, "form_responses", "responsesTable");
|
|
88
|
+
const responsesIndex = identifier(
|
|
89
|
+
`${options.responsesTable ?? "form_responses"}_lookup_idx`,
|
|
90
|
+
"form_responses_lookup_idx",
|
|
91
|
+
"responsesTable"
|
|
92
|
+
);
|
|
93
|
+
let migration;
|
|
94
|
+
const ensureReady = async () => {
|
|
95
|
+
if (options.autoMigrate !== true) return;
|
|
96
|
+
migration ??= options.client.query(`
|
|
97
|
+
CREATE TABLE IF NOT EXISTS ${schemasTable} (
|
|
98
|
+
form_id TEXT NOT NULL,
|
|
99
|
+
form_version INTEGER NOT NULL,
|
|
100
|
+
schema_json JSONB NOT NULL,
|
|
101
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
102
|
+
PRIMARY KEY (form_id, form_version)
|
|
103
|
+
);
|
|
104
|
+
CREATE TABLE IF NOT EXISTS ${responsesTable} (
|
|
105
|
+
response_id TEXT PRIMARY KEY,
|
|
106
|
+
form_id TEXT NOT NULL,
|
|
107
|
+
form_version INTEGER NOT NULL,
|
|
108
|
+
locale TEXT NOT NULL,
|
|
109
|
+
submitted_at TIMESTAMPTZ NOT NULL,
|
|
110
|
+
submission_json JSONB NOT NULL
|
|
111
|
+
);
|
|
112
|
+
CREATE INDEX IF NOT EXISTS ${responsesIndex}
|
|
113
|
+
ON ${responsesTable} (form_id, submitted_at, response_id);
|
|
114
|
+
`).then(() => void 0);
|
|
115
|
+
await migration;
|
|
116
|
+
};
|
|
117
|
+
return {
|
|
118
|
+
async saveSchema(schema) {
|
|
119
|
+
await ensureReady();
|
|
120
|
+
(0, import_core.assertValidFormSchema)(schema);
|
|
121
|
+
await options.client.query(
|
|
122
|
+
`INSERT INTO ${schemasTable} (form_id, form_version, schema_json, updated_at)
|
|
123
|
+
VALUES ($1, $2, $3::jsonb, CURRENT_TIMESTAMP)
|
|
124
|
+
ON CONFLICT (form_id, form_version) DO UPDATE
|
|
125
|
+
SET schema_json = EXCLUDED.schema_json, updated_at = CURRENT_TIMESTAMP`,
|
|
126
|
+
[schema.id, schema.version, JSON.stringify(schema)]
|
|
127
|
+
);
|
|
128
|
+
},
|
|
129
|
+
async getSchema(formId, formVersion) {
|
|
130
|
+
await ensureReady();
|
|
131
|
+
const result = await options.client.query(
|
|
132
|
+
`SELECT form_id, form_version, schema_json FROM ${schemasTable} WHERE form_id = $1 AND form_version = $2`,
|
|
133
|
+
[formId, formVersion]
|
|
134
|
+
);
|
|
135
|
+
const row = result.rows[0];
|
|
136
|
+
return row === void 0 ? null : parseSchemaRow(row, 0);
|
|
137
|
+
},
|
|
138
|
+
async listSchemas() {
|
|
139
|
+
await ensureReady();
|
|
140
|
+
const result = await options.client.query(
|
|
141
|
+
`SELECT form_id, form_version, schema_json FROM ${schemasTable} ORDER BY form_id, form_version`
|
|
142
|
+
);
|
|
143
|
+
return result.rows.map(parseSchemaRow);
|
|
144
|
+
},
|
|
145
|
+
async deleteSchema(formId, formVersion) {
|
|
146
|
+
await ensureReady();
|
|
147
|
+
await options.client.query(`DELETE FROM ${schemasTable} WHERE form_id = $1 AND form_version = $2`, [
|
|
148
|
+
formId,
|
|
149
|
+
formVersion
|
|
150
|
+
]);
|
|
151
|
+
},
|
|
152
|
+
async saveSubmission(submission) {
|
|
153
|
+
await ensureReady();
|
|
154
|
+
const stored = parseSubmission(submission, `input "${String(submission?.id)}"`);
|
|
155
|
+
await options.client.query(
|
|
156
|
+
`INSERT INTO ${responsesTable}
|
|
157
|
+
(response_id, form_id, form_version, locale, submitted_at, submission_json)
|
|
158
|
+
VALUES ($1, $2, $3, $4, $5::timestamptz, $6::jsonb)`,
|
|
159
|
+
[stored.id, stored.formId, stored.formVersion, stored.locale, stored.submittedAt, JSON.stringify(stored)]
|
|
160
|
+
);
|
|
161
|
+
},
|
|
162
|
+
async listSubmissions(formId, formVersion, queryOptions) {
|
|
163
|
+
await ensureReady();
|
|
164
|
+
const conditions = ["form_id = $1"];
|
|
165
|
+
const params = [formId];
|
|
166
|
+
if (formVersion !== void 0) {
|
|
167
|
+
params.push(formVersion);
|
|
168
|
+
conditions.push(`form_version = $${params.length}`);
|
|
169
|
+
}
|
|
170
|
+
if (queryOptions?.since !== void 0) {
|
|
171
|
+
params.push(queryOptions.since);
|
|
172
|
+
conditions.push(`submitted_at >= $${params.length}::timestamptz`);
|
|
173
|
+
}
|
|
174
|
+
if (queryOptions?.until !== void 0) {
|
|
175
|
+
params.push(queryOptions.until);
|
|
176
|
+
conditions.push(`submitted_at <= $${params.length}::timestamptz`);
|
|
177
|
+
}
|
|
178
|
+
const result = await options.client.query(
|
|
179
|
+
`SELECT response_id, form_id, form_version, locale, submitted_at, submission_json
|
|
180
|
+
FROM ${responsesTable} WHERE ${conditions.join(" AND ")} ORDER BY submitted_at, response_id`,
|
|
181
|
+
params
|
|
182
|
+
);
|
|
183
|
+
return result.rows.map(parseSubmissionRow);
|
|
184
|
+
},
|
|
185
|
+
async deleteSubmission(submissionId) {
|
|
186
|
+
await ensureReady();
|
|
187
|
+
await options.client.query(`DELETE FROM ${responsesTable} WHERE response_id = $1`, [submissionId]);
|
|
188
|
+
},
|
|
189
|
+
async clearResponses(formId) {
|
|
190
|
+
await ensureReady();
|
|
191
|
+
await options.client.query(`DELETE FROM ${responsesTable} WHERE form_id = $1`, [formId]);
|
|
192
|
+
},
|
|
193
|
+
async clear() {
|
|
194
|
+
await ensureReady();
|
|
195
|
+
await options.client.query(`DELETE FROM ${responsesTable}`);
|
|
196
|
+
await options.client.query(`DELETE FROM ${schemasTable}`);
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
201
|
+
0 && (module.exports = {
|
|
202
|
+
createPostgresStorage
|
|
203
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { FormStorageAdapter } from '@form-engine-ts/core';
|
|
2
|
+
|
|
3
|
+
interface PostgresClientLike {
|
|
4
|
+
query(text: string, params?: unknown[]): Promise<{
|
|
5
|
+
readonly rows: readonly unknown[];
|
|
6
|
+
}>;
|
|
7
|
+
}
|
|
8
|
+
interface PostgresStorageOptions {
|
|
9
|
+
readonly client: PostgresClientLike;
|
|
10
|
+
readonly schemasTable?: string;
|
|
11
|
+
readonly responsesTable?: string;
|
|
12
|
+
readonly autoMigrate?: boolean;
|
|
13
|
+
}
|
|
14
|
+
declare function createPostgresStorage(options: PostgresStorageOptions): FormStorageAdapter;
|
|
15
|
+
|
|
16
|
+
export { type PostgresClientLike, type PostgresStorageOptions, createPostgresStorage };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { FormStorageAdapter } from '@form-engine-ts/core';
|
|
2
|
+
|
|
3
|
+
interface PostgresClientLike {
|
|
4
|
+
query(text: string, params?: unknown[]): Promise<{
|
|
5
|
+
readonly rows: readonly unknown[];
|
|
6
|
+
}>;
|
|
7
|
+
}
|
|
8
|
+
interface PostgresStorageOptions {
|
|
9
|
+
readonly client: PostgresClientLike;
|
|
10
|
+
readonly schemasTable?: string;
|
|
11
|
+
readonly responsesTable?: string;
|
|
12
|
+
readonly autoMigrate?: boolean;
|
|
13
|
+
}
|
|
14
|
+
declare function createPostgresStorage(options: PostgresStorageOptions): FormStorageAdapter;
|
|
15
|
+
|
|
16
|
+
export { type PostgresClientLike, type PostgresStorageOptions, createPostgresStorage };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { assertValidFormSchema } from "@form-engine-ts/core";
|
|
3
|
+
function isRecord(value) {
|
|
4
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
function isFormValue(value) {
|
|
7
|
+
return value === void 0 || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
8
|
+
}
|
|
9
|
+
function cloneJson(value) {
|
|
10
|
+
return JSON.parse(JSON.stringify(value));
|
|
11
|
+
}
|
|
12
|
+
function parseJson(value, location) {
|
|
13
|
+
if (typeof value !== "string") return cloneJson(value);
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(value);
|
|
16
|
+
} catch (cause) {
|
|
17
|
+
throw new Error(`Postgres JSON at ${location} is invalid.`, { cause });
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function parseSubmission(value, location) {
|
|
21
|
+
const parsed = parseJson(value, location);
|
|
22
|
+
if (!isRecord(parsed) || typeof parsed.id !== "string" || typeof parsed.formId !== "string" || !Number.isInteger(parsed.formVersion) || typeof parsed.locale !== "string" || typeof parsed.submittedAt !== "string" || !isRecord(parsed.values) || !Object.values(parsed.values).every(isFormValue)) {
|
|
23
|
+
throw new Error(`Postgres submission at ${location} is invalid.`);
|
|
24
|
+
}
|
|
25
|
+
return cloneJson(parsed);
|
|
26
|
+
}
|
|
27
|
+
function parseSchemaRow(value, index) {
|
|
28
|
+
if (!isRecord(value)) throw new Error(`Postgres schema row ${index} is invalid.`);
|
|
29
|
+
const row = value;
|
|
30
|
+
const schema = parseJson(row.schema_json, `schema row ${index}`);
|
|
31
|
+
try {
|
|
32
|
+
assertValidFormSchema(schema);
|
|
33
|
+
} catch (cause) {
|
|
34
|
+
throw new Error(`Postgres schema row ${index} is invalid.`, { cause });
|
|
35
|
+
}
|
|
36
|
+
if (row.form_id !== schema.id || row.form_version !== schema.version) {
|
|
37
|
+
throw new Error(`Postgres schema row ${index} has inconsistent metadata.`);
|
|
38
|
+
}
|
|
39
|
+
return cloneJson(schema);
|
|
40
|
+
}
|
|
41
|
+
function parseSubmissionRow(value, index) {
|
|
42
|
+
if (!isRecord(value)) throw new Error(`Postgres submission row ${index} is invalid.`);
|
|
43
|
+
const row = value;
|
|
44
|
+
const submission = parseSubmission(row.submission_json, `submission row ${index}`);
|
|
45
|
+
const timestamp = row.submitted_at instanceof Date ? row.submitted_at.toISOString() : row.submitted_at;
|
|
46
|
+
if (row.response_id !== submission.id || row.form_id !== submission.formId || row.form_version !== submission.formVersion || row.locale !== submission.locale || typeof timestamp !== "string" || Date.parse(timestamp) !== Date.parse(submission.submittedAt)) {
|
|
47
|
+
throw new Error(`Postgres submission row ${index} has inconsistent metadata.`);
|
|
48
|
+
}
|
|
49
|
+
return submission;
|
|
50
|
+
}
|
|
51
|
+
function identifier(value, fallback, optionName) {
|
|
52
|
+
const name = value ?? fallback;
|
|
53
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
54
|
+
throw new TypeError(`${optionName} must be a safe SQL identifier.`);
|
|
55
|
+
}
|
|
56
|
+
return `"${name}"`;
|
|
57
|
+
}
|
|
58
|
+
function createPostgresStorage(options) {
|
|
59
|
+
if (options?.client === void 0 || typeof options.client.query !== "function") {
|
|
60
|
+
throw new TypeError("client with a query function is required.");
|
|
61
|
+
}
|
|
62
|
+
const schemasTable = identifier(options.schemasTable, "form_schemas", "schemasTable");
|
|
63
|
+
const responsesTable = identifier(options.responsesTable, "form_responses", "responsesTable");
|
|
64
|
+
const responsesIndex = identifier(
|
|
65
|
+
`${options.responsesTable ?? "form_responses"}_lookup_idx`,
|
|
66
|
+
"form_responses_lookup_idx",
|
|
67
|
+
"responsesTable"
|
|
68
|
+
);
|
|
69
|
+
let migration;
|
|
70
|
+
const ensureReady = async () => {
|
|
71
|
+
if (options.autoMigrate !== true) return;
|
|
72
|
+
migration ??= options.client.query(`
|
|
73
|
+
CREATE TABLE IF NOT EXISTS ${schemasTable} (
|
|
74
|
+
form_id TEXT NOT NULL,
|
|
75
|
+
form_version INTEGER NOT NULL,
|
|
76
|
+
schema_json JSONB NOT NULL,
|
|
77
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
78
|
+
PRIMARY KEY (form_id, form_version)
|
|
79
|
+
);
|
|
80
|
+
CREATE TABLE IF NOT EXISTS ${responsesTable} (
|
|
81
|
+
response_id TEXT PRIMARY KEY,
|
|
82
|
+
form_id TEXT NOT NULL,
|
|
83
|
+
form_version INTEGER NOT NULL,
|
|
84
|
+
locale TEXT NOT NULL,
|
|
85
|
+
submitted_at TIMESTAMPTZ NOT NULL,
|
|
86
|
+
submission_json JSONB NOT NULL
|
|
87
|
+
);
|
|
88
|
+
CREATE INDEX IF NOT EXISTS ${responsesIndex}
|
|
89
|
+
ON ${responsesTable} (form_id, submitted_at, response_id);
|
|
90
|
+
`).then(() => void 0);
|
|
91
|
+
await migration;
|
|
92
|
+
};
|
|
93
|
+
return {
|
|
94
|
+
async saveSchema(schema) {
|
|
95
|
+
await ensureReady();
|
|
96
|
+
assertValidFormSchema(schema);
|
|
97
|
+
await options.client.query(
|
|
98
|
+
`INSERT INTO ${schemasTable} (form_id, form_version, schema_json, updated_at)
|
|
99
|
+
VALUES ($1, $2, $3::jsonb, CURRENT_TIMESTAMP)
|
|
100
|
+
ON CONFLICT (form_id, form_version) DO UPDATE
|
|
101
|
+
SET schema_json = EXCLUDED.schema_json, updated_at = CURRENT_TIMESTAMP`,
|
|
102
|
+
[schema.id, schema.version, JSON.stringify(schema)]
|
|
103
|
+
);
|
|
104
|
+
},
|
|
105
|
+
async getSchema(formId, formVersion) {
|
|
106
|
+
await ensureReady();
|
|
107
|
+
const result = await options.client.query(
|
|
108
|
+
`SELECT form_id, form_version, schema_json FROM ${schemasTable} WHERE form_id = $1 AND form_version = $2`,
|
|
109
|
+
[formId, formVersion]
|
|
110
|
+
);
|
|
111
|
+
const row = result.rows[0];
|
|
112
|
+
return row === void 0 ? null : parseSchemaRow(row, 0);
|
|
113
|
+
},
|
|
114
|
+
async listSchemas() {
|
|
115
|
+
await ensureReady();
|
|
116
|
+
const result = await options.client.query(
|
|
117
|
+
`SELECT form_id, form_version, schema_json FROM ${schemasTable} ORDER BY form_id, form_version`
|
|
118
|
+
);
|
|
119
|
+
return result.rows.map(parseSchemaRow);
|
|
120
|
+
},
|
|
121
|
+
async deleteSchema(formId, formVersion) {
|
|
122
|
+
await ensureReady();
|
|
123
|
+
await options.client.query(`DELETE FROM ${schemasTable} WHERE form_id = $1 AND form_version = $2`, [
|
|
124
|
+
formId,
|
|
125
|
+
formVersion
|
|
126
|
+
]);
|
|
127
|
+
},
|
|
128
|
+
async saveSubmission(submission) {
|
|
129
|
+
await ensureReady();
|
|
130
|
+
const stored = parseSubmission(submission, `input "${String(submission?.id)}"`);
|
|
131
|
+
await options.client.query(
|
|
132
|
+
`INSERT INTO ${responsesTable}
|
|
133
|
+
(response_id, form_id, form_version, locale, submitted_at, submission_json)
|
|
134
|
+
VALUES ($1, $2, $3, $4, $5::timestamptz, $6::jsonb)`,
|
|
135
|
+
[stored.id, stored.formId, stored.formVersion, stored.locale, stored.submittedAt, JSON.stringify(stored)]
|
|
136
|
+
);
|
|
137
|
+
},
|
|
138
|
+
async listSubmissions(formId, formVersion, queryOptions) {
|
|
139
|
+
await ensureReady();
|
|
140
|
+
const conditions = ["form_id = $1"];
|
|
141
|
+
const params = [formId];
|
|
142
|
+
if (formVersion !== void 0) {
|
|
143
|
+
params.push(formVersion);
|
|
144
|
+
conditions.push(`form_version = $${params.length}`);
|
|
145
|
+
}
|
|
146
|
+
if (queryOptions?.since !== void 0) {
|
|
147
|
+
params.push(queryOptions.since);
|
|
148
|
+
conditions.push(`submitted_at >= $${params.length}::timestamptz`);
|
|
149
|
+
}
|
|
150
|
+
if (queryOptions?.until !== void 0) {
|
|
151
|
+
params.push(queryOptions.until);
|
|
152
|
+
conditions.push(`submitted_at <= $${params.length}::timestamptz`);
|
|
153
|
+
}
|
|
154
|
+
const result = await options.client.query(
|
|
155
|
+
`SELECT response_id, form_id, form_version, locale, submitted_at, submission_json
|
|
156
|
+
FROM ${responsesTable} WHERE ${conditions.join(" AND ")} ORDER BY submitted_at, response_id`,
|
|
157
|
+
params
|
|
158
|
+
);
|
|
159
|
+
return result.rows.map(parseSubmissionRow);
|
|
160
|
+
},
|
|
161
|
+
async deleteSubmission(submissionId) {
|
|
162
|
+
await ensureReady();
|
|
163
|
+
await options.client.query(`DELETE FROM ${responsesTable} WHERE response_id = $1`, [submissionId]);
|
|
164
|
+
},
|
|
165
|
+
async clearResponses(formId) {
|
|
166
|
+
await ensureReady();
|
|
167
|
+
await options.client.query(`DELETE FROM ${responsesTable} WHERE form_id = $1`, [formId]);
|
|
168
|
+
},
|
|
169
|
+
async clear() {
|
|
170
|
+
await ensureReady();
|
|
171
|
+
await options.client.query(`DELETE FROM ${responsesTable}`);
|
|
172
|
+
await options.client.query(`DELETE FROM ${schemasTable}`);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
export {
|
|
177
|
+
createPostgresStorage
|
|
178
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@form-engine-ts/storage-postgres",
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public"
|
|
6
|
+
},
|
|
7
|
+
"type": "module",
|
|
8
|
+
"sideEffects": false,
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"README.md",
|
|
12
|
+
"LICENSE"
|
|
13
|
+
],
|
|
14
|
+
"main": "./dist/index.cjs",
|
|
15
|
+
"module": "./dist/index.js",
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"import": "./dist/index.js",
|
|
21
|
+
"require": "./dist/index.cjs"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/nitta-a/form-engine-ts.git",
|
|
28
|
+
"directory": "packages/storage-postgres"
|
|
29
|
+
},
|
|
30
|
+
"bugs": {
|
|
31
|
+
"url": "https://github.com/nitta-a/form-engine-ts/issues"
|
|
32
|
+
},
|
|
33
|
+
"homepage": "https://github.com/nitta-a/form-engine-ts#readme",
|
|
34
|
+
"keywords": [
|
|
35
|
+
"form",
|
|
36
|
+
"survey",
|
|
37
|
+
"storage",
|
|
38
|
+
"postgresql",
|
|
39
|
+
"typescript"
|
|
40
|
+
],
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@form-engine-ts/core": "1.1.0"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"pg": "^8.11.0"
|
|
46
|
+
},
|
|
47
|
+
"peerDependenciesMeta": {
|
|
48
|
+
"pg": {
|
|
49
|
+
"optional": true
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@types/pg": "^8.11.0",
|
|
54
|
+
"pg": "^8.11.0"
|
|
55
|
+
},
|
|
56
|
+
"scripts": {
|
|
57
|
+
"build": "tsup src/index.ts --format esm,cjs --dts --clean --external @form-engine-ts/core --external pg",
|
|
58
|
+
"check": "biome check . && tsc --noEmit",
|
|
59
|
+
"test": "vitest run --globals",
|
|
60
|
+
"typecheck": "tsc --noEmit"
|
|
61
|
+
}
|
|
62
|
+
}
|