@appweaver/data 2.5.0 → 2.6.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/README.md +4 -2
- package/config.d.ts +1 -0
- package/config.js +1 -0
- package/database/database-config.d.ts +9 -0
- package/database/database-config.js +56 -1
- package/database/database-error.d.ts +8 -0
- package/database/database-error.js +18 -0
- package/database/prisma-database.js +16 -5
- package/database/setup-database.d.ts +23 -0
- package/database/setup-database.js +59 -0
- package/database/sqlserver-extension.js +21 -107
- package/database/telemetry-extension.d.ts +10 -0
- package/database/telemetry-extension.js +52 -0
- package/export/export-service.js +4 -0
- package/factory/create-model.d.ts +1 -1
- package/factory/create-model.js +75 -4
- package/factory/create-service.js +8 -0
- package/index.d.ts +2 -0
- package/index.js +5 -0
- package/internal.d.ts +2 -0
- package/internal.js +3 -1
- package/module.js +6 -3
- package/package.json +3 -3
- package/resource/resource-service.d.ts +32 -7
- package/resource/resource-service.js +244 -35
- package/resource/schemas/resource-filter-schema.d.ts +8 -0
- package/resource/schemas/resource-filter-schema.js +40 -1
- package/resource/schemas/resource-sort-schema.js +10 -0
- package/resource/utils/cursor-util.d.ts +13 -0
- package/resource/utils/cursor-util.js +21 -0
- package/resource/utils/filter-util.d.ts +9 -0
- package/resource/utils/filter-util.js +17 -0
- package/resource/utils/sort-util.d.ts +14 -0
- package/resource/utils/sort-util.js +1 -0
- package/resource/utils/where-util.d.ts +20 -0
- package/resource/utils/where-util.js +210 -0
- package/seeder/create-seeder.d.ts +3 -0
- package/seeder/create-seeder.js +1 -1
- package/seeder/seeder.d.ts +4 -2
- package/seeder/seeder.js +56 -23
- package/spatial/geo-schema.d.ts +22 -0
- package/spatial/geo-schema.js +60 -0
- package/spatial/spatial-config.d.ts +21 -0
- package/spatial/spatial-config.js +52 -0
- package/spatial/spatial-engine.d.ts +78 -0
- package/spatial/spatial-engine.js +232 -0
- package/spatial/spatial-extension.d.ts +10 -0
- package/spatial/spatial-extension.js +100 -0
- package/spatial/spatial-service.d.ts +54 -0
- package/spatial/spatial-service.js +213 -0
- package/spatial/utils/box-util.d.ts +31 -0
- package/spatial/utils/box-util.js +62 -0
- package/timeseries/database-time-series.js +2 -13
- package/timeseries/timescale-config.d.ts +1 -1
- package/timeseries/timescale-time-series.d.ts +6 -4
- package/timeseries/timescale-time-series.js +46 -19
- package/utils/schema-util.d.ts +8 -0
- package/utils/schema-util.js +22 -0
- package/utils/write-data-util.d.ts +22 -0
- package/utils/write-data-util.js +144 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.boxWithinFilter = boxWithinFilter;
|
|
4
|
+
exports.boxOverlapFilter = boxOverlapFilter;
|
|
5
|
+
exports.existsFilter = existsFilter;
|
|
6
|
+
const common_1 = require("@appweaver/common");
|
|
7
|
+
/**
|
|
8
|
+
* The condition of the bounding box columns of the geometries covered by one of the boxes, which is exact: a
|
|
9
|
+
* geometry lies in a box when its own box does. The upper bounds of the minimums repeat the ones of the maximums,
|
|
10
|
+
* for the index on the minimums.
|
|
11
|
+
*
|
|
12
|
+
* @param {string} field - The geo field.
|
|
13
|
+
* @param {GeoBox[]} boxes - The boxes.
|
|
14
|
+
* @return {Object} The Prisma condition.
|
|
15
|
+
*/
|
|
16
|
+
function boxWithinFilter(field, boxes) {
|
|
17
|
+
const columns = (0, common_1.geoColumns)(field);
|
|
18
|
+
return anyOf(boxes.map(([minLng, minLat, maxLng, maxLat]) => ({
|
|
19
|
+
[columns.minLng]: { gte: minLng, lte: maxLng },
|
|
20
|
+
[columns.minLat]: { gte: minLat, lte: maxLat },
|
|
21
|
+
[columns.maxLng]: { lte: maxLng },
|
|
22
|
+
[columns.maxLat]: { lte: maxLat }
|
|
23
|
+
})));
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The condition of the bounding box columns of the geometries whose box overlaps one of the boxes, the only ones
|
|
27
|
+
* that can share a point with it.
|
|
28
|
+
*
|
|
29
|
+
* @param {string} field - The geo field.
|
|
30
|
+
* @param {GeoBox[]} boxes - The boxes.
|
|
31
|
+
* @param {boolean} [point=false] - Whether the field holds points, whose minimums equal their maximums, so the
|
|
32
|
+
* index on the minimums bounds both sides.
|
|
33
|
+
* @return {Object} The Prisma condition.
|
|
34
|
+
*/
|
|
35
|
+
function boxOverlapFilter(field, boxes, point = false) {
|
|
36
|
+
const columns = (0, common_1.geoColumns)(field);
|
|
37
|
+
return anyOf(boxes.map(([minLng, minLat, maxLng, maxLat]) => point
|
|
38
|
+
? {
|
|
39
|
+
[columns.minLng]: { gte: minLng, lte: maxLng },
|
|
40
|
+
[columns.minLat]: { gte: minLat, lte: maxLat }
|
|
41
|
+
}
|
|
42
|
+
: {
|
|
43
|
+
[columns.minLng]: { lte: maxLng },
|
|
44
|
+
[columns.minLat]: { lte: maxLat },
|
|
45
|
+
[columns.maxLng]: { gte: minLng },
|
|
46
|
+
[columns.maxLat]: { gte: minLat }
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The condition of the records with a value of a geo field, or without one. The bounding box columns are null
|
|
51
|
+
* exactly when the geometry is, whichever null its JSON column holds.
|
|
52
|
+
*
|
|
53
|
+
* @param {string} field - The geo field.
|
|
54
|
+
* @param {boolean} exists - Whether the records have a value.
|
|
55
|
+
* @return {Object} The Prisma condition.
|
|
56
|
+
*/
|
|
57
|
+
function existsFilter(field, exists) {
|
|
58
|
+
return { [(0, common_1.geoColumns)(field).minLng]: exists ? { not: null } : null };
|
|
59
|
+
}
|
|
60
|
+
function anyOf(conditions) {
|
|
61
|
+
return conditions.length === 1 ? conditions[0] : { OR: conditions };
|
|
62
|
+
}
|
|
@@ -5,6 +5,7 @@ const common_1 = require("@appweaver/common");
|
|
|
5
5
|
const core_1 = require("@appweaver/core");
|
|
6
6
|
const database_config_1 = require("../database/database-config");
|
|
7
7
|
const database_error_1 = require("../database/database-error");
|
|
8
|
+
const schema_util_1 = require("../utils/schema-util");
|
|
8
9
|
const database_series_config_1 = require("./database-series-config");
|
|
9
10
|
const series_sql_util_1 = require("./utils/series-sql-util");
|
|
10
11
|
const logger = (0, common_1.createLogger)('timeseries');
|
|
@@ -26,7 +27,7 @@ class DatabaseTimeSeries extends common_1.TimeSeries {
|
|
|
26
27
|
/** @internal */
|
|
27
28
|
_type = (0, common_1.resolveDatabaseType)(database_config_1.databaseConfig.TYPE, database_config_1.databaseConfig.URL);
|
|
28
29
|
/** The PostgreSQL schema of the connection, `public` without one. @internal */
|
|
29
|
-
_schema = postgresSchema(this._type);
|
|
30
|
+
_schema = (0, schema_util_1.postgresSchema)(this._type);
|
|
30
31
|
/** @internal */
|
|
31
32
|
_dialect = (0, series_sql_util_1.seriesDialect)(this._type, this._schema);
|
|
32
33
|
/** @internal */
|
|
@@ -144,15 +145,3 @@ function seconds(duration, option) {
|
|
|
144
145
|
}
|
|
145
146
|
return value;
|
|
146
147
|
}
|
|
147
|
-
/** The `schema` parameter of a PostgreSQL URL, which the Prisma client leaves out of the raw queries. */
|
|
148
|
-
function postgresSchema(type) {
|
|
149
|
-
if (type !== common_1.DatabaseType.PostgreSQL) {
|
|
150
|
-
return undefined;
|
|
151
|
-
}
|
|
152
|
-
try {
|
|
153
|
-
return new URL(database_config_1.databaseConfig.URL).searchParams.get('schema') ?? undefined;
|
|
154
|
-
}
|
|
155
|
-
catch {
|
|
156
|
-
return undefined;
|
|
157
|
-
}
|
|
158
|
-
}
|
|
@@ -8,11 +8,13 @@ import { DatabaseTimeSeries } from './database-time-series';
|
|
|
8
8
|
export declare class TimescaleTimeSeries extends DatabaseTimeSeries {
|
|
9
9
|
static [HEALTH_CHECK]: boolean;
|
|
10
10
|
/**
|
|
11
|
-
* Creates the extension when missing, turns the series tables into hypertables and applies their
|
|
12
|
-
* an advisory lock, so the instances starting together set them up once.
|
|
11
|
+
* Creates the extension when missing, turns the series tables into hypertables and applies their chunk interval and
|
|
12
|
+
* policies, under an advisory lock, so the instances starting together set them up once. Only what differs from the
|
|
13
|
+
* models and the config is changed, so a database set up by `weaver migrate` runs no DDL, and the user of the
|
|
14
|
+
* application needs no privilege beyond reading and writing the data.
|
|
13
15
|
*
|
|
14
|
-
* @throws {ConfigurationError} `CONFIGURATION_INVALID` on a database other than PostgreSQL,
|
|
15
|
-
* TimescaleDB extension that cannot be created.
|
|
16
|
+
* @throws {ConfigurationError} `CONFIGURATION_INVALID` on a database other than PostgreSQL, one without the
|
|
17
|
+
* TimescaleDB extension that cannot be created, or one the user of the connection lacks the privileges to set up.
|
|
16
18
|
*/
|
|
17
19
|
register(models: SeriesModel[]): Promise<void>;
|
|
18
20
|
protected bucket(column: string, width: number): string;
|
|
@@ -4,6 +4,7 @@ exports.TimescaleTimeSeries = void 0;
|
|
|
4
4
|
const common_1 = require("@appweaver/common");
|
|
5
5
|
const client_1 = require("@prisma/client/runtime/client");
|
|
6
6
|
const database_config_1 = require("../database/database-config");
|
|
7
|
+
const database_error_1 = require("../database/database-error");
|
|
7
8
|
const database_time_series_1 = require("./database-time-series");
|
|
8
9
|
const timescale_config_1 = require("./timescale-config");
|
|
9
10
|
const logger = (0, common_1.createLogger)('timeseries');
|
|
@@ -27,11 +28,13 @@ const RETENTION = {
|
|
|
27
28
|
class TimescaleTimeSeries extends database_time_series_1.DatabaseTimeSeries {
|
|
28
29
|
static [common_1.HEALTH_CHECK] = false;
|
|
29
30
|
/**
|
|
30
|
-
* Creates the extension when missing, turns the series tables into hypertables and applies their
|
|
31
|
-
* an advisory lock, so the instances starting together set them up once.
|
|
31
|
+
* Creates the extension when missing, turns the series tables into hypertables and applies their chunk interval and
|
|
32
|
+
* policies, under an advisory lock, so the instances starting together set them up once. Only what differs from the
|
|
33
|
+
* models and the config is changed, so a database set up by `weaver migrate` runs no DDL, and the user of the
|
|
34
|
+
* application needs no privilege beyond reading and writing the data.
|
|
32
35
|
*
|
|
33
|
-
* @throws {ConfigurationError} `CONFIGURATION_INVALID` on a database other than PostgreSQL,
|
|
34
|
-
* TimescaleDB extension that cannot be created.
|
|
36
|
+
* @throws {ConfigurationError} `CONFIGURATION_INVALID` on a database other than PostgreSQL, one without the
|
|
37
|
+
* TimescaleDB extension that cannot be created, or one the user of the connection lacks the privileges to set up.
|
|
35
38
|
*/
|
|
36
39
|
async register(models) {
|
|
37
40
|
const type = (0, common_1.resolveDatabaseType)(database_config_1.databaseConfig.TYPE, database_config_1.databaseConfig.URL);
|
|
@@ -42,40 +45,64 @@ class TimescaleTimeSeries extends database_time_series_1.DatabaseTimeSeries {
|
|
|
42
45
|
return;
|
|
43
46
|
}
|
|
44
47
|
await this.ensureExtension();
|
|
45
|
-
|
|
46
|
-
await
|
|
47
|
-
|
|
48
|
-
|
|
48
|
+
try {
|
|
49
|
+
await this._db.transaction(async (tx) => {
|
|
50
|
+
await tx.$executeRawUnsafe(`SELECT pg_advisory_xact_lock(hashtext('appweaver:timeseries'))`);
|
|
51
|
+
for (const model of models) {
|
|
52
|
+
await this.setupHypertable(tx, model);
|
|
53
|
+
}
|
|
54
|
+
}, { timeout: timescale_config_1.timescaleConfig.SETUP_TIMEOUT });
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
if ((0, database_error_1.isPrivilegeError)(error)) {
|
|
58
|
+
throw new common_1.ConfigurationError(common_1.ErrorCode.ConfigurationInvalid, 'The time series hypertables are not set up, and the database user lacks the privileges to set them up, ' +
|
|
59
|
+
'run `weaver migrate`, which sets them up with the user of database.migrationUrl', undefined, { cause: error });
|
|
49
60
|
}
|
|
50
|
-
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
51
63
|
}
|
|
52
64
|
bucket(column, width) {
|
|
53
65
|
return `time_bucket(INTERVAL '${width} seconds', ${column}, TIMESTAMP '1970-01-01 00:00:00')`;
|
|
54
66
|
}
|
|
55
67
|
/** @internal */
|
|
56
68
|
async ensureExtension() {
|
|
57
|
-
const
|
|
58
|
-
if (
|
|
69
|
+
const installed = async (db) => (await db.$queryRaw((0, client_1.sqltag) `SELECT extversion FROM pg_extension WHERE extname = 'timescaledb'`)).length > 0;
|
|
70
|
+
if (await installed(this.client())) {
|
|
59
71
|
return;
|
|
60
72
|
}
|
|
61
73
|
try {
|
|
62
|
-
|
|
63
|
-
|
|
74
|
+
// Under the lock of the setup, since a CREATE EXTENSION IF NOT EXISTS
|
|
75
|
+
// racing another instance starting fails with a unique violation
|
|
76
|
+
await this._db.transaction(async (tx) => {
|
|
77
|
+
await tx.$executeRawUnsafe(`SELECT pg_advisory_xact_lock(hashtext('appweaver:timeseries'))`);
|
|
78
|
+
if (!(await installed(tx))) {
|
|
79
|
+
await tx.$executeRawUnsafe('CREATE EXTENSION IF NOT EXISTS timescaledb');
|
|
80
|
+
logger.info('Created the timescaledb extension');
|
|
81
|
+
}
|
|
82
|
+
}, { timeout: timescale_config_1.timescaleConfig.SETUP_TIMEOUT });
|
|
64
83
|
}
|
|
65
84
|
catch (error) {
|
|
66
85
|
throw new common_1.ConfigurationError(common_1.ErrorCode.ConfigurationInvalid, 'The timescaledb extension is not installed in the database and cannot be created, ' +
|
|
67
|
-
'create it with `CREATE EXTENSION timescaledb`
|
|
86
|
+
'create it with `CREATE EXTENSION timescaledb`, run `weaver migrate`, which creates it with the user of ' +
|
|
87
|
+
'database.migrationUrl, or use a TimescaleDB image', undefined, { cause: error });
|
|
68
88
|
}
|
|
69
89
|
}
|
|
70
90
|
/** @internal */
|
|
71
91
|
async setupHypertable(tx, model) {
|
|
72
92
|
const table = this.regclass(model.table);
|
|
73
93
|
const chunk = interval(model.options.chunkInterval ?? timescale_config_1.timescaleConfig.CHUNK_INTERVAL, 'chunkInterval');
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
94
|
+
const [dimension] = await tx.$queryRaw((0, client_1.sqltag) `SELECT time_interval = ${(0, client_1.raw)(`INTERVAL '${chunk}'`)} AS same FROM timescaledb_information.dimensions
|
|
95
|
+
WHERE hypertable_schema = ${this._schema ?? (0, client_1.raw)('current_schema()')} AND hypertable_name = ${model.table}
|
|
96
|
+
AND column_name = 'time'`);
|
|
97
|
+
if (!dimension) {
|
|
98
|
+
// The primary key holds the time, and no other index is created, so the
|
|
99
|
+
// schema stays the one of the Prisma migrations
|
|
100
|
+
await tx.$executeRawUnsafe(`SELECT create_hypertable('${table}', by_range('time', INTERVAL '${chunk}'), ` +
|
|
101
|
+
'if_not_exists => TRUE, create_default_indexes => FALSE, migrate_data => TRUE)');
|
|
102
|
+
}
|
|
103
|
+
else if (!dimension.same) {
|
|
104
|
+
await tx.$executeRawUnsafe(`SELECT set_chunk_time_interval('${table}', INTERVAL '${chunk}')`);
|
|
105
|
+
}
|
|
79
106
|
const compressAfter = model.options.compressAfter ?? timescale_config_1.timescaleConfig.COMPRESS_AFTER;
|
|
80
107
|
if (compressAfter) {
|
|
81
108
|
const [settings] = await tx.$queryRaw((0, client_1.sqltag) `SELECT compression_enabled FROM timescaledb_information.hypertables
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { DatabaseType } from '@appweaver/common';
|
|
2
|
+
/**
|
|
3
|
+
* The `schema` parameter of a PostgreSQL URL, which the Prisma client leaves out of the raw queries.
|
|
4
|
+
*
|
|
5
|
+
* @param {DatabaseType} type - The database type.
|
|
6
|
+
* @return {string | undefined} The schema, undefined for another database or a URL without one.
|
|
7
|
+
*/
|
|
8
|
+
export declare function postgresSchema(type: DatabaseType): string | undefined;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.postgresSchema = postgresSchema;
|
|
4
|
+
const common_1 = require("@appweaver/common");
|
|
5
|
+
const database_config_1 = require("../database/database-config");
|
|
6
|
+
/**
|
|
7
|
+
* The `schema` parameter of a PostgreSQL URL, which the Prisma client leaves out of the raw queries.
|
|
8
|
+
*
|
|
9
|
+
* @param {DatabaseType} type - The database type.
|
|
10
|
+
* @return {string | undefined} The schema, undefined for another database or a URL without one.
|
|
11
|
+
*/
|
|
12
|
+
function postgresSchema(type) {
|
|
13
|
+
if (type !== common_1.DatabaseType.PostgreSQL) {
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
try {
|
|
17
|
+
return new URL(database_config_1.databaseConfig.URL).searchParams.get('schema') ?? undefined;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Maps the data of a record a write stores, the nested writes of its relations excluded. */
|
|
2
|
+
export type RecordMapper = (modelName: string, data: Record<string, any>) => Record<string, any>;
|
|
3
|
+
/**
|
|
4
|
+
* Maps the data of the records a write operation stores, and of the nested writes of their relations, i.e. to
|
|
5
|
+
* serialize the JSON fields of SQL Server.
|
|
6
|
+
*
|
|
7
|
+
* @param {string} modelName - The model the operation runs on.
|
|
8
|
+
* @param {string} operation - The Prisma operation, i.e. `create`.
|
|
9
|
+
* @param {any} args - The arguments of the operation.
|
|
10
|
+
* @param {RecordMapper} mapRecord - Maps the data of a record.
|
|
11
|
+
* @return {any} The mapped arguments.
|
|
12
|
+
*/
|
|
13
|
+
export declare function mapWriteArgs(modelName: string, operation: string, args: any, mapRecord: RecordMapper): any;
|
|
14
|
+
/**
|
|
15
|
+
* Maps the records of a result, and of their included relations, i.e. to parse the JSON fields of SQL Server.
|
|
16
|
+
*
|
|
17
|
+
* @param {string} modelName - The model of the records.
|
|
18
|
+
* @param {any} result - The result, a record or a list of them.
|
|
19
|
+
* @param {RecordMapper} mapRecord - Maps a record.
|
|
20
|
+
* @return {any} The mapped result.
|
|
21
|
+
*/
|
|
22
|
+
export declare function mapResultRecords(modelName: string, result: any, mapRecord: RecordMapper): any;
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.mapWriteArgs = mapWriteArgs;
|
|
4
|
+
exports.mapResultRecords = mapResultRecords;
|
|
5
|
+
const common_1 = require("@appweaver/common");
|
|
6
|
+
const internal_1 = require("@appweaver/core/internal");
|
|
7
|
+
let cached;
|
|
8
|
+
/**
|
|
9
|
+
* Maps the data of the records a write operation stores, and of the nested writes of their relations, i.e. to
|
|
10
|
+
* serialize the JSON fields of SQL Server.
|
|
11
|
+
*
|
|
12
|
+
* @param {string} modelName - The model the operation runs on.
|
|
13
|
+
* @param {string} operation - The Prisma operation, i.e. `create`.
|
|
14
|
+
* @param {any} args - The arguments of the operation.
|
|
15
|
+
* @param {RecordMapper} mapRecord - Maps the data of a record.
|
|
16
|
+
* @return {any} The mapped arguments.
|
|
17
|
+
*/
|
|
18
|
+
function mapWriteArgs(modelName, operation, args, mapRecord) {
|
|
19
|
+
if (!(0, common_1.isPlainObject)(args)) {
|
|
20
|
+
return args;
|
|
21
|
+
}
|
|
22
|
+
const related = relatedModels();
|
|
23
|
+
const map = (data) => mapWriteData(modelName, data, mapRecord, related);
|
|
24
|
+
switch (operation) {
|
|
25
|
+
case 'create':
|
|
26
|
+
case 'createMany':
|
|
27
|
+
case 'createManyAndReturn':
|
|
28
|
+
case 'update':
|
|
29
|
+
case 'updateMany':
|
|
30
|
+
case 'updateManyAndReturn':
|
|
31
|
+
return { ...args, data: map(args.data) };
|
|
32
|
+
case 'upsert':
|
|
33
|
+
return { ...args, create: map(args.create), update: map(args.update) };
|
|
34
|
+
default:
|
|
35
|
+
return args;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Maps the records of a result, and of their included relations, i.e. to parse the JSON fields of SQL Server.
|
|
40
|
+
*
|
|
41
|
+
* @param {string} modelName - The model of the records.
|
|
42
|
+
* @param {any} result - The result, a record or a list of them.
|
|
43
|
+
* @param {RecordMapper} mapRecord - Maps a record.
|
|
44
|
+
* @return {any} The mapped result.
|
|
45
|
+
*/
|
|
46
|
+
function mapResultRecords(modelName, result, mapRecord) {
|
|
47
|
+
return mapRecords(modelName, result, mapRecord, relatedModels());
|
|
48
|
+
}
|
|
49
|
+
function mapRecords(modelName, result, mapRecord, related) {
|
|
50
|
+
if ((0, common_1.isArray)(result)) {
|
|
51
|
+
return result.map((item) => mapRecords(modelName, item, mapRecord, related));
|
|
52
|
+
}
|
|
53
|
+
if (!(0, common_1.isPlainObject)(result)) {
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
const record = mapRecord(modelName, result);
|
|
57
|
+
const fields = related.get(modelName);
|
|
58
|
+
for (const [key, value] of Object.entries(record)) {
|
|
59
|
+
if (fields?.has(key) && value !== null) {
|
|
60
|
+
record[key] = mapRecords(fields.get(key), value, mapRecord, related);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return record;
|
|
64
|
+
}
|
|
65
|
+
/** The related models of the loaded models, recomputed when the models change. */
|
|
66
|
+
function relatedModels() {
|
|
67
|
+
const loaded = [
|
|
68
|
+
...internal_1.context.resource.models.values()
|
|
69
|
+
];
|
|
70
|
+
if (cached?.models.length === loaded.length &&
|
|
71
|
+
cached.models.every((model, i) => model === loaded[i])) {
|
|
72
|
+
return cached.related;
|
|
73
|
+
}
|
|
74
|
+
const authModel = loaded.find(common_1.isResourceAuthModel);
|
|
75
|
+
const related = new Map();
|
|
76
|
+
for (const model of loaded) {
|
|
77
|
+
const fields = new Map();
|
|
78
|
+
for (const [field, relation] of Object.entries(model.config.relations ?? {})) {
|
|
79
|
+
fields.set(field, (0, common_1.capitalize)(relation.model));
|
|
80
|
+
}
|
|
81
|
+
for (const field of Object.keys(model.config.files ?? {})) {
|
|
82
|
+
fields.set(field, 'File');
|
|
83
|
+
}
|
|
84
|
+
if (authModel) {
|
|
85
|
+
fields.set('createdBy', authModel.name);
|
|
86
|
+
fields.set('deletedBy', authModel.name);
|
|
87
|
+
}
|
|
88
|
+
related.set(model.name, fields);
|
|
89
|
+
}
|
|
90
|
+
cached = { models: loaded, related };
|
|
91
|
+
return related;
|
|
92
|
+
}
|
|
93
|
+
function mapWriteData(modelName, data, mapRecord, related) {
|
|
94
|
+
if ((0, common_1.isArray)(data)) {
|
|
95
|
+
return data.map((item) => mapWriteData(modelName, item, mapRecord, related));
|
|
96
|
+
}
|
|
97
|
+
if (!(0, common_1.isPlainObject)(data)) {
|
|
98
|
+
return data;
|
|
99
|
+
}
|
|
100
|
+
const mapped = mapRecord(modelName, data);
|
|
101
|
+
const fields = related.get(modelName);
|
|
102
|
+
for (const [key, value] of Object.entries(mapped)) {
|
|
103
|
+
if (fields?.has(key) && (0, common_1.isPlainObject)(value)) {
|
|
104
|
+
mapped[key] = mapNestedWrites(fields.get(key), value, mapRecord, related);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return mapped;
|
|
108
|
+
}
|
|
109
|
+
function mapNestedWrites(modelName, writes, mapRecord, related) {
|
|
110
|
+
const map = (data) => mapWriteData(modelName, data, mapRecord, related);
|
|
111
|
+
const each = (value, fn) => (0, common_1.isArray)(value) ? value.map(fn) : fn(value);
|
|
112
|
+
const withData = (item) => (0, common_1.isPlainObject)(item) && 'data' in item
|
|
113
|
+
? { ...item, data: map(item.data) }
|
|
114
|
+
: map(item);
|
|
115
|
+
const mapped = { ...writes };
|
|
116
|
+
for (const [action, value] of Object.entries(writes)) {
|
|
117
|
+
switch (action) {
|
|
118
|
+
case 'create':
|
|
119
|
+
mapped[action] = map(value);
|
|
120
|
+
break;
|
|
121
|
+
case 'createMany':
|
|
122
|
+
mapped[action] = { ...value, data: map(value?.data) };
|
|
123
|
+
break;
|
|
124
|
+
case 'update':
|
|
125
|
+
case 'updateMany':
|
|
126
|
+
mapped[action] = each(value, withData);
|
|
127
|
+
break;
|
|
128
|
+
case 'upsert':
|
|
129
|
+
mapped[action] = each(value, (item) => ({
|
|
130
|
+
...item,
|
|
131
|
+
create: map(item?.create),
|
|
132
|
+
update: map(item?.update)
|
|
133
|
+
}));
|
|
134
|
+
break;
|
|
135
|
+
case 'connectOrCreate':
|
|
136
|
+
mapped[action] = each(value, (item) => ({
|
|
137
|
+
...item,
|
|
138
|
+
create: map(item?.create)
|
|
139
|
+
}));
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return mapped;
|
|
144
|
+
}
|