dynamo-bao 0.4.2 → 0.5.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/bin/bao-rebuild-search-text.js +62 -0
- package/bin/codegen.js +5 -31
- package/bin/dynamo-bao-update-table.js +37 -0
- package/bin/generators/model.js +13 -1
- package/bin/lib/create-table-params.js +5 -0
- package/bin/lib/process-models.js +114 -0
- package/package.json +3 -2
- package/src/constants.js +16 -1
- package/src/mixins/mutation-mixin.js +17 -0
- package/src/mixins/validation-mixin.js +34 -0
- package/src/model-manager.js +11 -0
- package/src/model.js +193 -13
- package/src/utils/search-text.js +206 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// Walks every row of a searchable model via iterateAll and re-saves with
|
|
4
|
+
// forceReindex: true so the save-time _searchText computation runs and the
|
|
5
|
+
// row's _searchText attribute is populated. Use after turning a model
|
|
6
|
+
// `searchable: true` on a model with existing data.
|
|
7
|
+
|
|
8
|
+
const resolve = require("./lib/resolve");
|
|
9
|
+
const { initModels, runWithBatchContext } = resolve("src/index.js");
|
|
10
|
+
const { initConfig } = resolve("src/config.js");
|
|
11
|
+
|
|
12
|
+
const modelName = process.argv[2];
|
|
13
|
+
if (!modelName) {
|
|
14
|
+
console.error("Usage: bao-rebuild-search-text <ModelName>");
|
|
15
|
+
process.exit(1);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
(async () => {
|
|
19
|
+
const config = await initConfig();
|
|
20
|
+
const manager = initModels(config);
|
|
21
|
+
let ModelClass;
|
|
22
|
+
try {
|
|
23
|
+
ModelClass = manager.getModel(modelName);
|
|
24
|
+
} catch (err) {
|
|
25
|
+
console.error(`Model "${modelName}" not found.`);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (!ModelClass.searchable || !ModelClass.searchConfig) {
|
|
30
|
+
console.error(
|
|
31
|
+
`Model "${modelName}" is not configured as searchable. Add a ` +
|
|
32
|
+
`searchable: { fields: [...] } block in YAML and run codegen first.`,
|
|
33
|
+
);
|
|
34
|
+
process.exit(1);
|
|
35
|
+
}
|
|
36
|
+
if (!ModelClass.iterable) {
|
|
37
|
+
console.error(
|
|
38
|
+
`Model "${modelName}" is not iterable. Cannot bulk-rebuild via iterateAll.`,
|
|
39
|
+
);
|
|
40
|
+
process.exit(1);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
console.log(`Rebuilding _searchText for ${modelName}...`);
|
|
44
|
+
let total = 0;
|
|
45
|
+
|
|
46
|
+
await runWithBatchContext(async () => {
|
|
47
|
+
for await (const batch of ModelClass.iterateAll({ batchSize: 50 })) {
|
|
48
|
+
for (const item of batch) {
|
|
49
|
+
await item.save({ forceReindex: true });
|
|
50
|
+
total++;
|
|
51
|
+
if (total % 100 === 0) {
|
|
52
|
+
console.log(` rebuilt ${total} so far...`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
console.log(`Done. Rebuilt _searchText on ${total} ${modelName} item(s).`);
|
|
59
|
+
})().catch((err) => {
|
|
60
|
+
console.error("Error:", err);
|
|
61
|
+
process.exit(1);
|
|
62
|
+
});
|
package/bin/codegen.js
CHANGED
|
@@ -9,6 +9,7 @@ const { createLogger } = require("./utils/scriptLogger");
|
|
|
9
9
|
const resolve = require("./lib/resolve");
|
|
10
10
|
const FieldResolver = resolve("src/fieldResolver");
|
|
11
11
|
const { initConfig } = resolve("src/config");
|
|
12
|
+
const { applyModelDefaults } = require("./lib/process-models");
|
|
12
13
|
|
|
13
14
|
// const __dirname = __dirname;
|
|
14
15
|
|
|
@@ -50,38 +51,11 @@ async function loadModelDefinitions(definitionsPath, fieldResolver) {
|
|
|
50
51
|
}
|
|
51
52
|
}
|
|
52
53
|
|
|
53
|
-
//
|
|
54
|
-
|
|
55
|
-
// Default 'iterable' based on tableType
|
|
56
|
-
if (modelDef.iterable === undefined) {
|
|
57
|
-
if (modelDef.tableType === "mapping") {
|
|
58
|
-
logger.debug(
|
|
59
|
-
`Model "${modelName}" is a mapping table, defaulting 'iterable' to false.`,
|
|
60
|
-
);
|
|
61
|
-
modelDef.iterable = false;
|
|
62
|
-
} else {
|
|
63
|
-
logger.debug(
|
|
64
|
-
`Model "${modelName}" is a standard table, defaulting 'iterable' to true.`,
|
|
65
|
-
);
|
|
66
|
-
modelDef.iterable = true;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// Default 'iterationBuckets'
|
|
71
|
-
if (modelDef.iterationBuckets === undefined) {
|
|
72
|
-
if (modelDef.iterable) {
|
|
73
|
-
logger.debug(
|
|
74
|
-
`Model "${modelName}" is iterable, defaulting 'iterationBuckets' to 10.`,
|
|
75
|
-
);
|
|
76
|
-
modelDef.iterationBuckets = 10;
|
|
77
|
-
} else {
|
|
78
|
-
logger.debug(
|
|
79
|
-
`Model "${modelName}" is not iterable, defaulting 'iterationBuckets' to 0.`,
|
|
80
|
-
);
|
|
81
|
-
modelDef.iterationBuckets = 0;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
54
|
+
// Apply iterable/iterationBuckets/searchable defaults and validation.
|
|
55
|
+
applyModelDefaults(models);
|
|
84
56
|
|
|
57
|
+
// Handle mapping-table specific shape after defaults are applied.
|
|
58
|
+
for (const [modelName, modelDef] of Object.entries(models)) {
|
|
85
59
|
if (modelDef.mapping) {
|
|
86
60
|
// For mapping tables, merge mapping properties with regular model properties
|
|
87
61
|
models[modelName] = {
|
|
@@ -53,6 +53,8 @@ const EXPECTED_GSIS = [
|
|
|
53
53
|
Projection: { ProjectionType: "ALL" },
|
|
54
54
|
},
|
|
55
55
|
{
|
|
56
|
+
// Legacy iteration index — KEYS_ONLY. The package default still reads
|
|
57
|
+
// through this; existing tables keep working without changes.
|
|
56
58
|
IndexName: "iter_index",
|
|
57
59
|
KeySchema: [
|
|
58
60
|
{ AttributeName: "_iter_pk", KeyType: "HASH" },
|
|
@@ -60,6 +62,22 @@ const EXPECTED_GSIS = [
|
|
|
60
62
|
],
|
|
61
63
|
Projection: { ProjectionType: "KEYS_ONLY" },
|
|
62
64
|
},
|
|
65
|
+
{
|
|
66
|
+
// New search-capable iteration index. INCLUDEs _searchText so
|
|
67
|
+
// searchAll/searchBucket can filter on the GSI without a base read.
|
|
68
|
+
// Adding this index is non-destructive: it costs an extra GSI write per
|
|
69
|
+
// save, but iterateAll continues to use iter_index until the user opts
|
|
70
|
+
// in via `db.iterationIndexName: "iter_search_index"`.
|
|
71
|
+
IndexName: "iter_search_index",
|
|
72
|
+
KeySchema: [
|
|
73
|
+
{ AttributeName: "_iter_pk", KeyType: "HASH" },
|
|
74
|
+
{ AttributeName: "_iter_sk", KeyType: "RANGE" },
|
|
75
|
+
],
|
|
76
|
+
Projection: {
|
|
77
|
+
ProjectionType: "INCLUDE",
|
|
78
|
+
NonKeyAttributes: ["_searchText"],
|
|
79
|
+
},
|
|
80
|
+
},
|
|
63
81
|
];
|
|
64
82
|
|
|
65
83
|
// All attribute definitions that GSIs may reference
|
|
@@ -210,6 +228,25 @@ async function main() {
|
|
|
210
228
|
console.log("Checking GSIs...");
|
|
211
229
|
await checkAndAddMissingGSIs(tableName);
|
|
212
230
|
|
|
231
|
+
// Print next steps for users who just added iter_search_index for the
|
|
232
|
+
// first time. The package default keeps reading through iter_index, so
|
|
233
|
+
// adding the new GSI alone doesn't change runtime behavior — they need to
|
|
234
|
+
// flip the config.
|
|
235
|
+
const desc = await client.send(
|
|
236
|
+
new DescribeTableCommand({ TableName: tableName }),
|
|
237
|
+
);
|
|
238
|
+
const existingIndexNames = (desc.Table.GlobalSecondaryIndexes || []).map(
|
|
239
|
+
(g) => g.IndexName,
|
|
240
|
+
);
|
|
241
|
+
if (existingIndexNames.includes("iter_search_index")) {
|
|
242
|
+
console.log(
|
|
243
|
+
"\nTo enable search:\n" +
|
|
244
|
+
" 1) Set 'db.iterationIndexName: \"iter_search_index\"' in your config.\n" +
|
|
245
|
+
" 2) (If your model has existing rows) run 'bao-rebuild-search-text <ModelName>'.\n" +
|
|
246
|
+
" 3) (Optional, after verification) drop the legacy 'iter_index' GSI.",
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
|
|
213
250
|
// Check and enable TTL
|
|
214
251
|
console.log("\nChecking TTL...");
|
|
215
252
|
await checkAndEnableTTL(tableName);
|
package/bin/generators/model.js
CHANGED
|
@@ -123,6 +123,16 @@ function generateModelClass(
|
|
|
123
123
|
const iterable = modelConfig.iterable === true;
|
|
124
124
|
const iterationBuckets = modelConfig.iterationBuckets || 100;
|
|
125
125
|
|
|
126
|
+
// Handle searchable configuration. modelConfig.searchable is either `false`
|
|
127
|
+
// or a fully-validated object (validated by applyModelDefaults in
|
|
128
|
+
// bin/lib/process-models.js).
|
|
129
|
+
const searchable = !!(
|
|
130
|
+
modelConfig.searchable && typeof modelConfig.searchable === "object"
|
|
131
|
+
);
|
|
132
|
+
const searchConfigLiteral = searchable
|
|
133
|
+
? JSON.stringify(modelConfig.searchable)
|
|
134
|
+
: "null";
|
|
135
|
+
|
|
126
136
|
// Always need these
|
|
127
137
|
baseImports.add("PrimaryKeyConfig");
|
|
128
138
|
if (indexes) baseImports.add("IndexConfig");
|
|
@@ -231,7 +241,9 @@ class ${modelName} extends BaoModel {
|
|
|
231
241
|
static modelPrefix = '${modelConfig.modelPrefix}';
|
|
232
242
|
static iterable = ${iterable};
|
|
233
243
|
static iterationBuckets = ${iterationBuckets};
|
|
234
|
-
|
|
244
|
+
static searchable = ${searchable};
|
|
245
|
+
static searchConfig = ${searchConfigLiteral};
|
|
246
|
+
|
|
235
247
|
static fields = {
|
|
236
248
|
${fields}
|
|
237
249
|
};
|
|
@@ -62,6 +62,11 @@ const TABLE_PARAMS = {
|
|
|
62
62
|
Projection: { ProjectionType: "ALL" },
|
|
63
63
|
},
|
|
64
64
|
{
|
|
65
|
+
// Legacy iteration index (KEYS_ONLY). To enable search, run
|
|
66
|
+
// `bao-update-table` after package upgrade — it will add
|
|
67
|
+
// `iter_search_index` (INCLUDE projection on _searchText) alongside
|
|
68
|
+
// this one. Then set `db.iterationIndexName: "iter_search_index"` in
|
|
69
|
+
// your config to start using it.
|
|
65
70
|
IndexName: "iter_index",
|
|
66
71
|
KeySchema: [
|
|
67
72
|
{ AttributeName: "_iter_pk", KeyType: "HASH" },
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Pure function for normalizing and validating parsed model definitions
|
|
2
|
+
// before they hit codegen. Keeps validation testable in isolation and
|
|
3
|
+
// produces clear, model-scoped error messages.
|
|
4
|
+
|
|
5
|
+
const SEARCHABLE_KNOWN_OPTIONS = new Set([
|
|
6
|
+
"fields",
|
|
7
|
+
"caseSensitive",
|
|
8
|
+
"minTermLength",
|
|
9
|
+
"dedupe",
|
|
10
|
+
]);
|
|
11
|
+
|
|
12
|
+
function applyIterableDefaults(modelDef) {
|
|
13
|
+
if (modelDef.iterable === undefined) {
|
|
14
|
+
modelDef.iterable = modelDef.tableType !== "mapping";
|
|
15
|
+
}
|
|
16
|
+
if (modelDef.iterationBuckets === undefined) {
|
|
17
|
+
modelDef.iterationBuckets = modelDef.iterable ? 10 : 0;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function validateSearchable(modelName, modelDef) {
|
|
22
|
+
const raw = modelDef.searchable;
|
|
23
|
+
|
|
24
|
+
if (raw === undefined || raw === false) {
|
|
25
|
+
modelDef.searchable = false;
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (raw === true) {
|
|
30
|
+
throw new Error(
|
|
31
|
+
`Model "${modelName}": \`searchable: true\` is not supported. ` +
|
|
32
|
+
`Provide an object with \`fields\` listing the StringField names to index, ` +
|
|
33
|
+
`e.g. \`searchable: { fields: [title, body] }\`.`,
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (typeof raw !== "object" || Array.isArray(raw)) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
`Model "${modelName}": \`searchable\` must be either a boolean or an object. Got ${typeof raw}.`,
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
for (const key of Object.keys(raw)) {
|
|
44
|
+
if (!SEARCHABLE_KNOWN_OPTIONS.has(key)) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
`Model "${modelName}": \`searchable\` has unknown option "${key}". ` +
|
|
47
|
+
`Known options: ${Array.from(SEARCHABLE_KNOWN_OPTIONS).join(", ")}.`,
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (!Array.isArray(raw.fields) || raw.fields.length === 0) {
|
|
53
|
+
throw new Error(
|
|
54
|
+
`Model "${modelName}": \`searchable.fields\` must be a non-empty array of field names.`,
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
for (const fieldName of raw.fields) {
|
|
59
|
+
if (typeof fieldName !== "string") {
|
|
60
|
+
throw new Error(
|
|
61
|
+
`Model "${modelName}": \`searchable.fields\` entries must be strings. Got ${typeof fieldName}.`,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
const fieldDef = modelDef.fields && modelDef.fields[fieldName];
|
|
65
|
+
if (!fieldDef) {
|
|
66
|
+
throw new Error(
|
|
67
|
+
`Model "${modelName}": \`searchable.fields\` references "${fieldName}" but that field is not defined on the model.`,
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
if (fieldDef.type !== "StringField") {
|
|
71
|
+
throw new Error(
|
|
72
|
+
`Model "${modelName}": \`searchable.fields\` entry "${fieldName}" must be a StringField, got ${fieldDef.type}.`,
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (raw.caseSensitive !== undefined && typeof raw.caseSensitive !== "boolean") {
|
|
78
|
+
throw new Error(
|
|
79
|
+
`Model "${modelName}": \`searchable.caseSensitive\` must be a boolean.`,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (raw.dedupe !== undefined && typeof raw.dedupe !== "boolean") {
|
|
84
|
+
throw new Error(
|
|
85
|
+
`Model "${modelName}": \`searchable.dedupe\` must be a boolean.`,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (raw.minTermLength !== undefined) {
|
|
90
|
+
const n = raw.minTermLength;
|
|
91
|
+
if (typeof n !== "number" || !Number.isInteger(n) || n < 1) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
`Model "${modelName}": \`searchable.minTermLength\` must be a positive integer.`,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
modelDef.searchable = {
|
|
99
|
+
fields: raw.fields.slice(),
|
|
100
|
+
caseSensitive: raw.caseSensitive === true,
|
|
101
|
+
minTermLength: raw.minTermLength === undefined ? 1 : raw.minTermLength,
|
|
102
|
+
dedupe: raw.dedupe === true,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function applyModelDefaults(models) {
|
|
107
|
+
for (const [modelName, modelDef] of Object.entries(models)) {
|
|
108
|
+
applyIterableDefaults(modelDef);
|
|
109
|
+
validateSearchable(modelName, modelDef);
|
|
110
|
+
}
|
|
111
|
+
return models;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
module.exports = { applyModelDefaults };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dynamo-bao",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"exports": {
|
|
@@ -58,6 +58,7 @@
|
|
|
58
58
|
"bao-codegen": "./bin/codegen.js",
|
|
59
59
|
"bao-watch": "./bin/watch.js",
|
|
60
60
|
"bao-update-table": "./bin/dynamo-bao-update-table.js",
|
|
61
|
-
"bao-delete": "./bin/dynamo-bao-delete-table.js"
|
|
61
|
+
"bao-delete": "./bin/dynamo-bao-delete-table.js",
|
|
62
|
+
"bao-rebuild-search-text": "./bin/bao-rebuild-search-text.js"
|
|
62
63
|
}
|
|
63
64
|
}
|
package/src/constants.js
CHANGED
|
@@ -5,10 +5,21 @@ const GSI_INDEX_ID3 = "gsi3";
|
|
|
5
5
|
const GSI_INDEX_ID4 = "gsi4";
|
|
6
6
|
const GSI_INDEX_ID5 = "gsi5";
|
|
7
7
|
|
|
8
|
-
// Constants for iteration index
|
|
8
|
+
// Constants for iteration index. The package default is `iter_index` (the
|
|
9
|
+
// legacy KEYS_ONLY GSI) so an upgrade doesn't break iteration on tables that
|
|
10
|
+
// haven't been migrated yet. To enable search, users add the new
|
|
11
|
+
// `iter_search_index` GSI (via bao-update-table) and set
|
|
12
|
+
// `db.iterationIndexName: "iter_search_index"` in their config — see
|
|
13
|
+
// SEARCH_INDEX_NAME below.
|
|
9
14
|
const ITERATION_INDEX_NAME = "iter_index";
|
|
15
|
+
const SEARCH_INDEX_NAME = "iter_search_index";
|
|
10
16
|
const ITERATION_PK_FIELD = "_iter_pk";
|
|
11
17
|
const ITERATION_SK_FIELD = "_iter_sk";
|
|
18
|
+
const SEARCH_TEXT_FIELD = "_searchText";
|
|
19
|
+
|
|
20
|
+
// Backwards-compatibility alias so older code that imported the legacy name
|
|
21
|
+
// keeps working. Same value as ITERATION_INDEX_NAME.
|
|
22
|
+
const LEGACY_ITERATION_INDEX_NAME = ITERATION_INDEX_NAME;
|
|
12
23
|
|
|
13
24
|
// Constants for unique constraints
|
|
14
25
|
const UNIQUE_CONSTRAINT_ID1 = "_uc1";
|
|
@@ -31,6 +42,7 @@ const SYSTEM_FIELDS = [
|
|
|
31
42
|
"_gsi5_sk",
|
|
32
43
|
"_iter_pk",
|
|
33
44
|
"_iter_sk",
|
|
45
|
+
"_searchText",
|
|
34
46
|
];
|
|
35
47
|
|
|
36
48
|
const UNIQUE_CONSTRAINT_KEY = "_raft_uc";
|
|
@@ -42,8 +54,11 @@ module.exports = {
|
|
|
42
54
|
GSI_INDEX_ID4,
|
|
43
55
|
GSI_INDEX_ID5,
|
|
44
56
|
ITERATION_INDEX_NAME,
|
|
57
|
+
SEARCH_INDEX_NAME,
|
|
45
58
|
ITERATION_PK_FIELD,
|
|
46
59
|
ITERATION_SK_FIELD,
|
|
60
|
+
SEARCH_TEXT_FIELD,
|
|
61
|
+
LEGACY_ITERATION_INDEX_NAME,
|
|
47
62
|
UNIQUE_CONSTRAINT_ID1,
|
|
48
63
|
UNIQUE_CONSTRAINT_ID2,
|
|
49
64
|
UNIQUE_CONSTRAINT_ID3,
|
|
@@ -13,6 +13,8 @@ const {
|
|
|
13
13
|
ConditionalError,
|
|
14
14
|
ValidationError,
|
|
15
15
|
} = require("../exceptions");
|
|
16
|
+
const { computeSearchTextUpdate } = require("../utils/search-text");
|
|
17
|
+
const { SEARCH_TEXT_FIELD } = require("../constants");
|
|
16
18
|
|
|
17
19
|
const MutationMethods = {
|
|
18
20
|
/**
|
|
@@ -480,6 +482,21 @@ const MutationMethods = {
|
|
|
480
482
|
Object.assign(dyUpdatesToSave, iterationKeys);
|
|
481
483
|
}
|
|
482
484
|
|
|
485
|
+
// Compute _searchText if the model is searchable. Returns undefined to
|
|
486
|
+
// skip the write entirely, null to REMOVE, or a string to SET.
|
|
487
|
+
if (this.searchable && this.searchConfig) {
|
|
488
|
+
const searchTextValue = computeSearchTextUpdate({
|
|
489
|
+
searchConfig: this.searchConfig,
|
|
490
|
+
dyUpdatesToSave,
|
|
491
|
+
currentItem,
|
|
492
|
+
isNew,
|
|
493
|
+
forceReindex,
|
|
494
|
+
});
|
|
495
|
+
if (searchTextValue !== undefined) {
|
|
496
|
+
dyUpdatesToSave[SEARCH_TEXT_FIELD] = searchTextValue;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
483
500
|
// Build the update expression first
|
|
484
501
|
const { updateExpression, names, values } = this._buildUpdateExpression(
|
|
485
502
|
dyUpdatesToSave,
|
|
@@ -190,6 +190,40 @@ const ValidationMethods = {
|
|
|
190
190
|
this.iterable = false;
|
|
191
191
|
}
|
|
192
192
|
|
|
193
|
+
// Validate searchable configuration. Catches the case where a model has
|
|
194
|
+
// `searchable: true` but no `searchConfig` (e.g., hand-written class or
|
|
195
|
+
// partially-regenerated codebase) — better to fail loudly at registration
|
|
196
|
+
// than silently skip _searchText computation on every save.
|
|
197
|
+
if (this.searchable === true) {
|
|
198
|
+
if (!this.searchConfig || typeof this.searchConfig !== "object") {
|
|
199
|
+
throw new ConfigurationError(
|
|
200
|
+
`${this.name} has \`searchable: true\` but no \`searchConfig\`. ` +
|
|
201
|
+
`Re-run codegen, or set \`static searchConfig = { fields: [...] }\` ` +
|
|
202
|
+
`on the class.`,
|
|
203
|
+
this.name,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
if (
|
|
207
|
+
!Array.isArray(this.searchConfig.fields) ||
|
|
208
|
+
this.searchConfig.fields.length === 0
|
|
209
|
+
) {
|
|
210
|
+
throw new ConfigurationError(
|
|
211
|
+
`${this.name} \`searchConfig.fields\` must be a non-empty array.`,
|
|
212
|
+
this.name,
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
for (const fieldName of this.searchConfig.fields) {
|
|
216
|
+
const fieldDef = this.fields[fieldName];
|
|
217
|
+
if (!fieldDef) {
|
|
218
|
+
throw new ConfigurationError(
|
|
219
|
+
`${this.name} \`searchConfig.fields\` references "${fieldName}" but ` +
|
|
220
|
+
`that field is not defined on the model.`,
|
|
221
|
+
this.name,
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
193
227
|
// Validate unique constraints
|
|
194
228
|
const validConstraintIds = [
|
|
195
229
|
UNIQUE_CONSTRAINT_ID1,
|
package/src/model-manager.js
CHANGED
|
@@ -113,6 +113,17 @@ class ModelManager {
|
|
|
113
113
|
return this._tenantId;
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
+
// Resolved iteration index name. Defaults to "iter_search_index"; users
|
|
117
|
+
// mid-migration can override via config.db.iterationIndexName: "iter_index"
|
|
118
|
+
// to keep iteration on the legacy index. searchAll/searchBucket guard against
|
|
119
|
+
// the legacy value.
|
|
120
|
+
getIterationIndexName() {
|
|
121
|
+
return (
|
|
122
|
+
this._config?.db?.iterationIndexName ||
|
|
123
|
+
require("./constants").ITERATION_INDEX_NAME
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
116
127
|
// Backward compatibility
|
|
117
128
|
getTestId() {
|
|
118
129
|
return this._tenantId;
|
package/src/model.js
CHANGED
|
@@ -33,8 +33,10 @@ const {
|
|
|
33
33
|
UNIQUE_CONSTRAINT_KEY,
|
|
34
34
|
SYSTEM_FIELDS,
|
|
35
35
|
ITERATION_INDEX_NAME,
|
|
36
|
+
SEARCH_INDEX_NAME,
|
|
36
37
|
ITERATION_PK_FIELD,
|
|
37
38
|
ITERATION_SK_FIELD,
|
|
39
|
+
SEARCH_TEXT_FIELD,
|
|
38
40
|
} = require("./constants");
|
|
39
41
|
const {
|
|
40
42
|
ConfigurationError,
|
|
@@ -63,6 +65,8 @@ class BaoModel {
|
|
|
63
65
|
static uniqueConstraints = {};
|
|
64
66
|
static iterable = false;
|
|
65
67
|
static iterationBuckets = 100;
|
|
68
|
+
static searchable = false;
|
|
69
|
+
static searchConfig = null;
|
|
66
70
|
|
|
67
71
|
static defaultQueryLimit = 100;
|
|
68
72
|
|
|
@@ -269,21 +273,152 @@ class BaoModel {
|
|
|
269
273
|
yield* this._iterateSingleBucket(bucketNum, options);
|
|
270
274
|
}
|
|
271
275
|
|
|
272
|
-
static
|
|
273
|
-
|
|
274
|
-
|
|
276
|
+
static _assertSearchable() {
|
|
277
|
+
if (!this.searchable || !this.searchConfig) {
|
|
278
|
+
throw new Error(
|
|
279
|
+
`Model ${this.name} is not configured as searchable. ` +
|
|
280
|
+
`Add a searchable: { fields: [...] } block in YAML to enable search.`,
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
if (!this.iterable) {
|
|
284
|
+
throw new Error(
|
|
285
|
+
`searchAll requires iterable: true. For non-iterable models, use ` +
|
|
286
|
+
`query/queryByIndex with a filter on _searchText.`,
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
const indexName = this.manager.getIterationIndexName();
|
|
290
|
+
if (indexName !== SEARCH_INDEX_NAME) {
|
|
291
|
+
throw new Error(
|
|
292
|
+
`searchAll requires the '${SEARCH_INDEX_NAME}' GSI. Current config ` +
|
|
293
|
+
`resolves the iteration index to '${indexName}'. To enable search:\n` +
|
|
294
|
+
` 1) Run 'bao-update-table' to add ${SEARCH_INDEX_NAME} to the table.\n` +
|
|
295
|
+
` 2) Set 'db.iterationIndexName: "${SEARCH_INDEX_NAME}"' in your config.\n` +
|
|
296
|
+
` 3) (If the model already has data) run 'bao-rebuild-search-text <ModelName>'.`,
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
static async *searchAll(terms, options = {}) {
|
|
302
|
+
this._assertSearchable();
|
|
303
|
+
const {
|
|
304
|
+
buildSearchPredicate,
|
|
305
|
+
} = require("./utils/search-text");
|
|
306
|
+
const { operator = "$and", batchSize = 100, filter = null } = options;
|
|
307
|
+
const searchPredicate = buildSearchPredicate(terms, this.searchConfig, {
|
|
308
|
+
operator,
|
|
309
|
+
});
|
|
275
310
|
|
|
276
|
-
let iterPk;
|
|
277
311
|
if (this.iterationBuckets === 1) {
|
|
278
|
-
|
|
312
|
+
yield* this._iterateSingleBucket(null, {
|
|
313
|
+
batchSize,
|
|
314
|
+
filter,
|
|
315
|
+
searchPredicate,
|
|
316
|
+
});
|
|
317
|
+
} else {
|
|
318
|
+
for (let bucket = 0; bucket < this.iterationBuckets; bucket++) {
|
|
319
|
+
yield* this._iterateSingleBucket(bucket, {
|
|
320
|
+
batchSize,
|
|
321
|
+
filter,
|
|
322
|
+
searchPredicate,
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
static async *searchBucket(bucketNum, terms, options = {}) {
|
|
329
|
+
this._assertSearchable();
|
|
330
|
+
if (bucketNum < 0 || bucketNum >= this.iterationBuckets) {
|
|
331
|
+
throw new Error(
|
|
332
|
+
`Invalid bucket number ${bucketNum}. Must be 0-${this.iterationBuckets - 1}`,
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
const {
|
|
336
|
+
buildSearchPredicate,
|
|
337
|
+
} = require("./utils/search-text");
|
|
338
|
+
const { operator = "$and", batchSize = 100, filter = null } = options;
|
|
339
|
+
const searchPredicate = buildSearchPredicate(terms, this.searchConfig, {
|
|
340
|
+
operator,
|
|
341
|
+
});
|
|
342
|
+
yield* this._iterateSingleBucket(bucketNum, {
|
|
343
|
+
batchSize,
|
|
344
|
+
filter,
|
|
345
|
+
searchPredicate,
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
static tokenizeSearchQuery(queryString) {
|
|
350
|
+
const { tokenizeSearchQuery } = require("./utils/search-text");
|
|
351
|
+
return tokenizeSearchQuery(queryString);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// Normalize a single search term using the same rules the model used to
|
|
355
|
+
// build `_searchText`. Useful when post-filtering hydrated rows in JS:
|
|
356
|
+
// const term = Post.normalizeSearchTerm(userInput);
|
|
357
|
+
// results.filter(p => p._dyData._searchText?.includes(term));
|
|
358
|
+
static normalizeSearchTerm(term) {
|
|
359
|
+
const { normalizeSearchTerm } = require("./utils/search-text");
|
|
360
|
+
return normalizeSearchTerm(term, this.searchConfig || {});
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Attributes projected onto each iteration index, by index name. The base
|
|
364
|
+
// table key (_pk/_sk) and the index key (_iter_pk/_iter_sk) are always
|
|
365
|
+
// projected by DynamoDB. iter_search_index additionally INCLUDEs
|
|
366
|
+
// _searchText. iter_index (legacy) is KEYS_ONLY.
|
|
367
|
+
static _PROJECTED_ATTRS_BY_INDEX = {
|
|
368
|
+
[SEARCH_INDEX_NAME]: new Set([
|
|
369
|
+
"_pk",
|
|
370
|
+
"_sk",
|
|
371
|
+
ITERATION_PK_FIELD,
|
|
372
|
+
ITERATION_SK_FIELD,
|
|
373
|
+
SEARCH_TEXT_FIELD,
|
|
374
|
+
]),
|
|
375
|
+
[ITERATION_INDEX_NAME]: new Set([
|
|
376
|
+
"_pk",
|
|
377
|
+
"_sk",
|
|
378
|
+
ITERATION_PK_FIELD,
|
|
379
|
+
ITERATION_SK_FIELD,
|
|
380
|
+
]),
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
static _assertFilterFitsIterIndex(indexName, expressionAttributeNames) {
|
|
384
|
+
const projected = this._PROJECTED_ATTRS_BY_INDEX[indexName];
|
|
385
|
+
if (!projected) return; // Unknown index — skip the preflight.
|
|
386
|
+
const referenced = Object.values(expressionAttributeNames);
|
|
387
|
+
const unprojected = referenced.filter((name) => !projected.has(name));
|
|
388
|
+
if (unprojected.length === 0) return;
|
|
389
|
+
const list = unprojected.join(", ");
|
|
390
|
+
const example = unprojected[0];
|
|
391
|
+
const projectedList = Array.from(projected).join(", ");
|
|
392
|
+
throw new Error(
|
|
393
|
+
`Filter on '${indexName}' references attribute(s) that aren't ` +
|
|
394
|
+
`projected: [${list}]. The index projects: [${projectedList}]. ` +
|
|
395
|
+
`DynamoDB can't filter on anything else at the index level — ` +
|
|
396
|
+
`filter the hydrated batch in JS instead, e.g.:\n` +
|
|
397
|
+
` for await (const batch of Model.iterateAll()) {\n` +
|
|
398
|
+
` for (const item of batch) {\n` +
|
|
399
|
+
` if (item.${example} === ...) { /* keep */ }\n` +
|
|
400
|
+
` }\n` +
|
|
401
|
+
` }`,
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
static _getIterationPk(bucketNum) {
|
|
406
|
+
const tenantId = this.manager.getTenantId();
|
|
407
|
+
if (this.iterationBuckets === 1) {
|
|
408
|
+
return tenantId
|
|
279
409
|
? `[${tenantId}]#${this.modelPrefix}#iter`
|
|
280
410
|
: `${this.modelPrefix}#iter`;
|
|
281
|
-
} else {
|
|
282
|
-
const bucket = bucketNum.toString().padStart(3, "0");
|
|
283
|
-
iterPk = tenantId
|
|
284
|
-
? `[${tenantId}]#${this.modelPrefix}#iter#${bucket}`
|
|
285
|
-
: `${this.modelPrefix}#iter#${bucket}`;
|
|
286
411
|
}
|
|
412
|
+
const bucket = bucketNum.toString().padStart(3, "0");
|
|
413
|
+
return tenantId
|
|
414
|
+
? `[${tenantId}]#${this.modelPrefix}#iter#${bucket}`
|
|
415
|
+
: `${this.modelPrefix}#iter#${bucket}`;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
static async *_iterateSingleBucket(bucketNum, options = {}) {
|
|
419
|
+
const { batchSize = 100, filter = null, searchPredicate = null } = options;
|
|
420
|
+
const iterPk = this._getIterationPk(bucketNum);
|
|
421
|
+
const indexName = this.manager.getIterationIndexName();
|
|
287
422
|
|
|
288
423
|
let lastEvaluatedKey = null;
|
|
289
424
|
|
|
@@ -291,7 +426,7 @@ class BaoModel {
|
|
|
291
426
|
const { QueryCommand } = require("./dynamodb-client");
|
|
292
427
|
const params = {
|
|
293
428
|
TableName: this.table,
|
|
294
|
-
IndexName:
|
|
429
|
+
IndexName: indexName,
|
|
295
430
|
KeyConditionExpression: "#pk = :pk",
|
|
296
431
|
ExpressionAttributeNames: { "#pk": ITERATION_PK_FIELD },
|
|
297
432
|
ExpressionAttributeValues: { ":pk": iterPk },
|
|
@@ -303,12 +438,21 @@ class BaoModel {
|
|
|
303
438
|
params.ExclusiveStartKey = lastEvaluatedKey;
|
|
304
439
|
}
|
|
305
440
|
|
|
441
|
+
const filterParts = [];
|
|
306
442
|
if (filter) {
|
|
307
443
|
const { FilterExpressionBuilder } = require("./filter-expression");
|
|
308
444
|
const filterBuilder = new FilterExpressionBuilder();
|
|
309
445
|
const filterExpression = filterBuilder.build(filter, this);
|
|
310
446
|
if (filterExpression) {
|
|
311
|
-
|
|
447
|
+
// Preflight: filter attributes must be in the GSI's projection.
|
|
448
|
+
// Otherwise DynamoDB returns an opaque "does not project one or
|
|
449
|
+
// more filter attributes" ValidationException; we surface a clearer
|
|
450
|
+
// error before the round-trip.
|
|
451
|
+
this._assertFilterFitsIterIndex(
|
|
452
|
+
indexName,
|
|
453
|
+
filterExpression.ExpressionAttributeNames,
|
|
454
|
+
);
|
|
455
|
+
filterParts.push(filterExpression.FilterExpression);
|
|
312
456
|
Object.assign(
|
|
313
457
|
params.ExpressionAttributeNames,
|
|
314
458
|
filterExpression.ExpressionAttributeNames,
|
|
@@ -319,8 +463,44 @@ class BaoModel {
|
|
|
319
463
|
);
|
|
320
464
|
}
|
|
321
465
|
}
|
|
466
|
+
if (searchPredicate) {
|
|
467
|
+
filterParts.push(searchPredicate.FilterExpression);
|
|
468
|
+
Object.assign(
|
|
469
|
+
params.ExpressionAttributeNames,
|
|
470
|
+
searchPredicate.ExpressionAttributeNames,
|
|
471
|
+
);
|
|
472
|
+
Object.assign(
|
|
473
|
+
params.ExpressionAttributeValues,
|
|
474
|
+
searchPredicate.ExpressionAttributeValues,
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
if (filterParts.length > 0) {
|
|
478
|
+
params.FilterExpression = filterParts.map((p) => `(${p})`).join(" AND ");
|
|
479
|
+
}
|
|
322
480
|
|
|
323
|
-
|
|
481
|
+
let response;
|
|
482
|
+
try {
|
|
483
|
+
response = await this.documentClient.send(new QueryCommand(params));
|
|
484
|
+
} catch (error) {
|
|
485
|
+
// DynamoDB reports a missing index as a ValidationException with a
|
|
486
|
+
// message like "The table does not have the specified index: <name>".
|
|
487
|
+
// We only translate when the message explicitly references an index
|
|
488
|
+
// — translating raw ResourceNotFoundException would mask a missing
|
|
489
|
+
// *table* with a "run bao-update-table" hint that wouldn't help.
|
|
490
|
+
const message = error.message || "";
|
|
491
|
+
const isMissingIndex =
|
|
492
|
+
/does not have the specified index/i.test(message) ||
|
|
493
|
+
message.includes(`specified index: ${indexName}`) ||
|
|
494
|
+
(error.name === "ResourceNotFoundException" &&
|
|
495
|
+
message.toLowerCase().includes("index"));
|
|
496
|
+
if (isMissingIndex) {
|
|
497
|
+
throw new Error(
|
|
498
|
+
`Index '${indexName}' is missing on table '${this.table}'. ` +
|
|
499
|
+
`Run 'bao-update-table' to add it.`,
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
throw error;
|
|
503
|
+
}
|
|
324
504
|
|
|
325
505
|
if (response.Items && response.Items.length > 0) {
|
|
326
506
|
const objectIds = response.Items.map(
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// Pure helpers for searchable models. Kept dependency-free so they can be
|
|
2
|
+
// unit-tested in isolation and reused for both write-side index population
|
|
3
|
+
// and read-side query normalization.
|
|
4
|
+
|
|
5
|
+
const NON_ALPHANUM_REGEX = /[^\p{L}\p{N}\s]/gu;
|
|
6
|
+
const WHITESPACE_REGEX = /\s+/g;
|
|
7
|
+
|
|
8
|
+
function normalize(text, { caseSensitive = false } = {}) {
|
|
9
|
+
let result = String(text).replace(NON_ALPHANUM_REGEX, " ");
|
|
10
|
+
if (!caseSensitive) result = result.toLowerCase();
|
|
11
|
+
result = result.replace(WHITESPACE_REGEX, " ").trim();
|
|
12
|
+
return result;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function buildSearchText(values, config) {
|
|
16
|
+
const {
|
|
17
|
+
fields = [],
|
|
18
|
+
caseSensitive = false,
|
|
19
|
+
minTermLength = 1,
|
|
20
|
+
dedupe = false,
|
|
21
|
+
} = config || {};
|
|
22
|
+
|
|
23
|
+
const parts = [];
|
|
24
|
+
for (const fieldName of fields) {
|
|
25
|
+
const value = values[fieldName];
|
|
26
|
+
if (value === null || value === undefined) continue;
|
|
27
|
+
parts.push(String(value));
|
|
28
|
+
}
|
|
29
|
+
if (parts.length === 0) return "";
|
|
30
|
+
|
|
31
|
+
let text = normalize(parts.join(" "), { caseSensitive });
|
|
32
|
+
if (text === "") return "";
|
|
33
|
+
|
|
34
|
+
const needsTokenize = dedupe || (minTermLength && minTermLength > 1);
|
|
35
|
+
if (!needsTokenize) return text;
|
|
36
|
+
|
|
37
|
+
const tokens = text.split(" ");
|
|
38
|
+
const filtered = [];
|
|
39
|
+
const seen = new Set();
|
|
40
|
+
for (const tok of tokens) {
|
|
41
|
+
if (!tok) continue;
|
|
42
|
+
if (minTermLength > 1 && [...tok].length < minTermLength) continue;
|
|
43
|
+
if (dedupe) {
|
|
44
|
+
if (seen.has(tok)) continue;
|
|
45
|
+
seen.add(tok);
|
|
46
|
+
}
|
|
47
|
+
filtered.push(tok);
|
|
48
|
+
}
|
|
49
|
+
return filtered.join(" ");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function normalizeSearchTerm(term, config = {}) {
|
|
53
|
+
return normalize(term, config);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function tokenizeSearchQuery(query) {
|
|
57
|
+
if (typeof query !== "string") return [];
|
|
58
|
+
const tokens = [];
|
|
59
|
+
let i = 0;
|
|
60
|
+
const n = query.length;
|
|
61
|
+
while (i < n) {
|
|
62
|
+
const ch = query[i];
|
|
63
|
+
if (/\s/.test(ch)) {
|
|
64
|
+
i++;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (ch === '"') {
|
|
68
|
+
const close = query.indexOf('"', i + 1);
|
|
69
|
+
if (close === -1) {
|
|
70
|
+
const phrase = query.slice(i + 1).trim();
|
|
71
|
+
if (phrase) tokens.push(phrase);
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
const phrase = query.slice(i + 1, close).trim();
|
|
75
|
+
if (phrase) tokens.push(phrase);
|
|
76
|
+
i = close + 1;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
let j = i;
|
|
80
|
+
while (j < n && !/\s/.test(query[j]) && query[j] !== '"') j++;
|
|
81
|
+
const word = query.slice(i, j);
|
|
82
|
+
if (word) tokens.push(word);
|
|
83
|
+
i = j;
|
|
84
|
+
}
|
|
85
|
+
return tokens;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Decide what `_searchText` should be on a save.
|
|
89
|
+
//
|
|
90
|
+
// Returns:
|
|
91
|
+
// undefined → do not include `_searchText` in the update payload (leave the
|
|
92
|
+
// row's existing value untouched, or skip on insert).
|
|
93
|
+
// null → include `_searchText: null` (caller emits REMOVE).
|
|
94
|
+
// string → include `_searchText: <value>` (caller emits SET).
|
|
95
|
+
//
|
|
96
|
+
// Inputs:
|
|
97
|
+
// searchConfig: the validated `static searchConfig` object, or null.
|
|
98
|
+
// dyUpdatesToSave: the diff being written to DynamoDB (in Dy format —
|
|
99
|
+
// string fields stay as strings, so this is the same
|
|
100
|
+
// representation that buildSearchText reads).
|
|
101
|
+
// currentItem: the loaded model instance whose `_dyData` holds current
|
|
102
|
+
// values. Required for non-isNew updates so untouched source
|
|
103
|
+
// fields can be backfilled. May be null for insert.
|
|
104
|
+
// isNew: true on create.
|
|
105
|
+
// forceReindex: true when the caller wants every index attribute
|
|
106
|
+
// recomputed from the merged state regardless of which
|
|
107
|
+
// fields were touched.
|
|
108
|
+
function computeSearchTextUpdate({
|
|
109
|
+
searchConfig,
|
|
110
|
+
dyUpdatesToSave,
|
|
111
|
+
currentItem,
|
|
112
|
+
isNew = false,
|
|
113
|
+
forceReindex = false,
|
|
114
|
+
}) {
|
|
115
|
+
if (!searchConfig) return undefined;
|
|
116
|
+
|
|
117
|
+
const fields = searchConfig.fields || [];
|
|
118
|
+
const sourceTouched = fields.some((f) =>
|
|
119
|
+
Object.prototype.hasOwnProperty.call(dyUpdatesToSave, f),
|
|
120
|
+
);
|
|
121
|
+
|
|
122
|
+
if (!isNew && !forceReindex && !sourceTouched) return undefined;
|
|
123
|
+
|
|
124
|
+
const merged = {};
|
|
125
|
+
if (currentItem && currentItem._dyData) {
|
|
126
|
+
for (const f of fields) {
|
|
127
|
+
if (f in currentItem._dyData) merged[f] = currentItem._dyData[f];
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
for (const f of fields) {
|
|
131
|
+
if (Object.prototype.hasOwnProperty.call(dyUpdatesToSave, f)) {
|
|
132
|
+
merged[f] = dyUpdatesToSave[f];
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const result = buildSearchText(merged, searchConfig);
|
|
137
|
+
|
|
138
|
+
if (result === "") {
|
|
139
|
+
return isNew ? undefined : null;
|
|
140
|
+
}
|
|
141
|
+
return result;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Build a DynamoDB FilterExpression predicate that matches rows whose
|
|
145
|
+
// `_searchText` contains the supplied terms. Terms are normalized with the
|
|
146
|
+
// same rules used to build `_searchText` so the values match what's stored.
|
|
147
|
+
//
|
|
148
|
+
// Returns null-safe `{ FilterExpression, ExpressionAttributeNames,
|
|
149
|
+
// ExpressionAttributeValues }`. The caller is responsible for AND'ing this
|
|
150
|
+
// into any user-supplied filter.
|
|
151
|
+
const VALID_OPERATORS = new Set(["$and", "$or"]);
|
|
152
|
+
|
|
153
|
+
function buildSearchPredicate(terms, searchConfig, options = {}) {
|
|
154
|
+
if (!Array.isArray(terms)) {
|
|
155
|
+
throw new Error("terms must be an array of strings.");
|
|
156
|
+
}
|
|
157
|
+
for (const t of terms) {
|
|
158
|
+
if (typeof t !== "string") {
|
|
159
|
+
throw new Error("terms must be strings.");
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const { operator = "$and" } = options;
|
|
163
|
+
if (!VALID_OPERATORS.has(operator)) {
|
|
164
|
+
throw new Error(
|
|
165
|
+
`operator must be one of: ${Array.from(VALID_OPERATORS).join(", ")}.`,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const normalized = [];
|
|
170
|
+
for (const t of terms) {
|
|
171
|
+
const n = normalizeSearchTerm(t, searchConfig || {});
|
|
172
|
+
if (n) normalized.push(n);
|
|
173
|
+
}
|
|
174
|
+
if (normalized.length === 0) {
|
|
175
|
+
throw new Error("searchAll requires at least one non-empty term.");
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// `:stN` placeholders are deliberately a separate namespace from the
|
|
179
|
+
// FilterExpressionBuilder convention (`:vN`, see src/filter-expression.js)
|
|
180
|
+
// so the two can be merged into a single FilterExpression without colliding.
|
|
181
|
+
const join = operator === "$or" ? " OR " : " AND ";
|
|
182
|
+
const parts = [];
|
|
183
|
+
const values = {};
|
|
184
|
+
normalized.forEach((value, idx) => {
|
|
185
|
+
const key = `:st${idx}`;
|
|
186
|
+
parts.push(`contains(#st, ${key})`);
|
|
187
|
+
values[key] = value;
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
const expression =
|
|
191
|
+
parts.length === 1 ? parts[0] : parts.map((p) => `(${p})`).join(join);
|
|
192
|
+
|
|
193
|
+
return {
|
|
194
|
+
FilterExpression: expression,
|
|
195
|
+
ExpressionAttributeNames: { "#st": "_searchText" },
|
|
196
|
+
ExpressionAttributeValues: values,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
module.exports = {
|
|
201
|
+
buildSearchText,
|
|
202
|
+
normalizeSearchTerm,
|
|
203
|
+
tokenizeSearchQuery,
|
|
204
|
+
computeSearchTextUpdate,
|
|
205
|
+
buildSearchPredicate,
|
|
206
|
+
};
|