@webiny/api-core-ddb 6.6.0-alpha.0 → 6.6.0-alpha.10
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/adminUsers/index.js +7 -1
- package/adminUsers/index.js.map +1 -1
- package/keyValueStore/KeyValueStoreDynamoTable.d.ts +24 -0
- package/keyValueStore/KeyValueStoreDynamoTable.js +15 -0
- package/keyValueStore/KeyValueStoreDynamoTable.js.map +1 -1
- package/keyValueStore/KeyValueStoreStorageOperations.d.ts +13 -2
- package/keyValueStore/KeyValueStoreStorageOperations.js +158 -7
- package/keyValueStore/KeyValueStoreStorageOperations.js.map +1 -1
- package/package.json +11 -11
package/adminUsers/index.js
CHANGED
|
@@ -108,8 +108,14 @@ const createStorageOperations = (params)=>{
|
|
|
108
108
|
code: "LIST_ADMIN_USERS_ERROR"
|
|
109
109
|
});
|
|
110
110
|
}
|
|
111
|
+
const { id_in, teams_in } = where;
|
|
112
|
+
const filtered = items.filter((item)=>{
|
|
113
|
+
if (Array.isArray(id_in) && !id_in.includes(item.id)) return false;
|
|
114
|
+
if (Array.isArray(teams_in)) return (item.teams || []).some((team)=>teams_in.includes(team));
|
|
115
|
+
return true;
|
|
116
|
+
});
|
|
111
117
|
return sortItems({
|
|
112
|
-
items,
|
|
118
|
+
items: filtered,
|
|
113
119
|
sort
|
|
114
120
|
});
|
|
115
121
|
},
|
package/adminUsers/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adminUsers/index.js","sources":["../../src/adminUsers/index.ts"],"sourcesContent":["import type { AdminUsersStorageOperations, CreateAdminUsersStorageOperations } from \"./types.js\";\nimport WebinyError from \"@webiny/error\";\nimport { createTable, type IStandardEntityAttributes, sortItems } from \"@webiny/db-dynamodb\";\nimport { createUserEntity } from \"./definitions/entities.js\";\nimport type {\n AdminUser,\n StorageOperationsGetUserParams,\n StorageOperationsListUsersParams\n} from \"@webiny/api-core/types/users.js\";\n\nexport const createStorageOperations: CreateAdminUsersStorageOperations = params => {\n const { table: tableName, documentClient } = params;\n\n const table = createTable({\n name: tableName || (process.env.DB_TABLE as string),\n documentClient\n });\n\n const entities = {\n users: createUserEntity(table.table)\n };\n\n const createUserKeys = (user: Pick<AdminUser, \"tenant\" | \"id\">) => ({\n PK: `T#${user.tenant}#ADMIN_USER#${user.id}`,\n SK: `A`\n });\n\n const createUserGSIKeys = (user: AdminUser) => {\n return {\n GSI1_PK: `T#${user.tenant}#ADMIN_USERS`,\n GSI1_SK: user.email,\n GSI_TENANT: user.tenant\n };\n };\n\n const storageOperations: AdminUsersStorageOperations = {\n getTable() {\n return table;\n },\n getEntities() {\n return entities;\n },\n async createUser({ user }) {\n const keys = {\n ...createUserKeys(user),\n ...createUserGSIKeys(user)\n };\n\n try {\n await entities.users.put({\n ...keys,\n TYPE: \"adminUsers.user\",\n data: user\n });\n\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create admin user.\",\n code: \"CREATE_ADMIN_USER_ERROR\",\n data: { keys }\n });\n }\n },\n async deleteUser({ user }) {\n const keys = createUserKeys(user);\n\n try {\n await entities.users.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete group.\",\n code: \"CREATE_DELETE_ERROR\",\n data: { keys, user }\n });\n }\n },\n async getUser<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsGetUserParams\n ): Promise<TUser | null> {\n const {\n where: { tenant, id, email }\n } = params;\n try {\n if (id) {\n const response = await entities.users.get<IStandardEntityAttributes<TUser>>(\n createUserKeys({ tenant, id })\n );\n return (response?.data as TUser) || null;\n }\n\n const response = await entities.users.queryOne<IStandardEntityAttributes<TUser>>({\n partitionKey: `T#${tenant}#ADMIN_USERS`,\n options: {\n index: \"GSI1\",\n eq: email\n }\n });\n\n return (response?.data as TUser) || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load user.\",\n code: \"GET_ADMIN_USERS_ERROR\",\n data: { id, email }\n });\n }\n },\n async listUsers<TUser extends AdminUser = AdminUser>({\n where,\n sort\n }: StorageOperationsListUsersParams) {\n let items: TUser[];\n try {\n const ddbItems = await entities.users.queryAll<IStandardEntityAttributes<TUser>>({\n partitionKey: `T#${where.tenant}#ADMIN_USERS`,\n options: {\n index: \"GSI1\"\n }\n });\n items = ddbItems.map(item => {\n return item.data as TUser;\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list users.\",\n code: \"LIST_ADMIN_USERS_ERROR\"\n });\n }\n\n return sortItems({ items, sort });\n },\n async updateUser({ user }) {\n const keys = {\n ...createUserKeys(user),\n ...createUserGSIKeys(user)\n };\n\n try {\n await entities.users.put({\n ...keys,\n TYPE: \"adminUsers.user\",\n data: user\n });\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update user.\",\n code: \"UPDATE_ADMIN_USER_ERROR\",\n data: { keys, user }\n });\n }\n }\n };\n\n return storageOperations;\n};\n"],"names":["createStorageOperations","params","tableName","documentClient","table","createTable","process","entities","createUserEntity","createUserKeys","user","createUserGSIKeys","storageOperations","keys","err","WebinyError","tenant","id","email","response","where","sort","items","ddbItems","item","sortItems"],"mappings":";;;AAUO,MAAMA,0BAA6DC,CAAAA;IACtE,MAAM,EAAE,OAAOC,SAAS,EAAEC,cAAc,EAAE,GAAGF;IAE7C,MAAMG,QAAQC,YAAY;QACtB,MAAMH,aAAcI,QAAQ,GAAG,CAAC,QAAQ;QACxCH;IACJ;IAEA,MAAMI,WAAW;QACb,OAAOC,iBAAiBJ,MAAM,KAAK;IACvC;IAEA,MAAMK,iBAAiB,CAACC,OAA4C;YAChE,IAAI,CAAC,EAAE,EAAEA,KAAK,MAAM,CAAC,YAAY,EAAEA,KAAK,EAAE,EAAE;YAC5C,IAAI;QACR;IAEA,MAAMC,oBAAoB,CAACD,OAChB;YACH,SAAS,CAAC,EAAE,EAAEA,KAAK,MAAM,CAAC,YAAY,CAAC;YACvC,SAASA,KAAK,KAAK;YACnB,YAAYA,K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AAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEG;wBAAIC;oBAAM;gBACtB;YACJ;QACJ;QACA,MAAM,WAA+C,EACjDE,KAAK,EACLC,IAAI,EAC2B;YAC/B,IAAIC;YACJ,IAAI;gBACA,MAAMC,WAAW,MAAMhB,SAAS,KAAK,CAAC,QAAQ,CAAmC;oBAC7E,cAAc,CAAC,EAAE,EAAEa,MAAM,MAAM,CAAC,YAAY,CAAC;oBAC7C,SAAS;wBACL,OAAO;oBACX;gBACJ;gBACAE,QAAQC,SAAS,GAAG,CAACC,CAAAA,OACVA,KAAK,IAAI;YAExB,EAAE,OAAOV,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;gBACV;YACJ;YAEA,
|
|
1
|
+
{"version":3,"file":"adminUsers/index.js","sources":["../../src/adminUsers/index.ts"],"sourcesContent":["import type { AdminUsersStorageOperations, CreateAdminUsersStorageOperations } from \"./types.js\";\nimport WebinyError from \"@webiny/error\";\nimport { createTable, type IStandardEntityAttributes, sortItems } from \"@webiny/db-dynamodb\";\nimport { createUserEntity } from \"./definitions/entities.js\";\nimport type {\n AdminUser,\n StorageOperationsGetUserParams,\n StorageOperationsListUsersParams\n} from \"@webiny/api-core/types/users.js\";\n\nexport const createStorageOperations: CreateAdminUsersStorageOperations = params => {\n const { table: tableName, documentClient } = params;\n\n const table = createTable({\n name: tableName || (process.env.DB_TABLE as string),\n documentClient\n });\n\n const entities = {\n users: createUserEntity(table.table)\n };\n\n const createUserKeys = (user: Pick<AdminUser, \"tenant\" | \"id\">) => ({\n PK: `T#${user.tenant}#ADMIN_USER#${user.id}`,\n SK: `A`\n });\n\n const createUserGSIKeys = (user: AdminUser) => {\n return {\n GSI1_PK: `T#${user.tenant}#ADMIN_USERS`,\n GSI1_SK: user.email,\n GSI_TENANT: user.tenant\n };\n };\n\n const storageOperations: AdminUsersStorageOperations = {\n getTable() {\n return table;\n },\n getEntities() {\n return entities;\n },\n async createUser({ user }) {\n const keys = {\n ...createUserKeys(user),\n ...createUserGSIKeys(user)\n };\n\n try {\n await entities.users.put({\n ...keys,\n TYPE: \"adminUsers.user\",\n data: user\n });\n\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create admin user.\",\n code: \"CREATE_ADMIN_USER_ERROR\",\n data: { keys }\n });\n }\n },\n async deleteUser({ user }) {\n const keys = createUserKeys(user);\n\n try {\n await entities.users.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete group.\",\n code: \"CREATE_DELETE_ERROR\",\n data: { keys, user }\n });\n }\n },\n async getUser<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsGetUserParams\n ): Promise<TUser | null> {\n const {\n where: { tenant, id, email }\n } = params;\n try {\n if (id) {\n const response = await entities.users.get<IStandardEntityAttributes<TUser>>(\n createUserKeys({ tenant, id })\n );\n return (response?.data as TUser) || null;\n }\n\n const response = await entities.users.queryOne<IStandardEntityAttributes<TUser>>({\n partitionKey: `T#${tenant}#ADMIN_USERS`,\n options: {\n index: \"GSI1\",\n eq: email\n }\n });\n\n return (response?.data as TUser) || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load user.\",\n code: \"GET_ADMIN_USERS_ERROR\",\n data: { id, email }\n });\n }\n },\n async listUsers<TUser extends AdminUser = AdminUser>({\n where,\n sort\n }: StorageOperationsListUsersParams) {\n let items: TUser[];\n try {\n const ddbItems = await entities.users.queryAll<IStandardEntityAttributes<TUser>>({\n partitionKey: `T#${where.tenant}#ADMIN_USERS`,\n options: {\n index: \"GSI1\"\n }\n });\n items = ddbItems.map(item => {\n return item.data as TUser;\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list users.\",\n code: \"LIST_ADMIN_USERS_ERROR\"\n });\n }\n\n const { id_in, teams_in } = where;\n\n const filtered = items.filter(item => {\n if (Array.isArray(id_in) && !id_in.includes(item.id)) {\n return false;\n }\n if (Array.isArray(teams_in)) {\n return (item.teams || []).some(team => teams_in.includes(team));\n }\n return true;\n });\n\n return sortItems({ items: filtered, sort });\n },\n async updateUser({ user }) {\n const keys = {\n ...createUserKeys(user),\n ...createUserGSIKeys(user)\n };\n\n try {\n await entities.users.put({\n ...keys,\n TYPE: \"adminUsers.user\",\n data: user\n });\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update user.\",\n code: \"UPDATE_ADMIN_USER_ERROR\",\n data: { keys, user }\n });\n }\n }\n };\n\n return storageOperations;\n};\n"],"names":["createStorageOperations","params","tableName","documentClient","table","createTable","process","entities","createUserEntity","createUserKeys","user","createUserGSIKeys","storageOperations","keys","err","WebinyError","tenant","id","email","response","where","sort","items","ddbItems","item","id_in","teams_in","filtered","Array","team","sortItems"],"mappings":";;;AAUO,MAAMA,0BAA6DC,CAAAA;IACtE,MAAM,EAAE,OAAOC,SAAS,EAAEC,cAAc,EAAE,GAAGF;IAE7C,MAAMG,QAAQC,YAAY;QACtB,MAAMH,aAAcI,QAAQ,GAAG,CAAC,QAAQ;QACxCH;IACJ;IAEA,MAAMI,WAAW;QACb,OAAOC,iBAAiBJ,MAAM,KAAK;IACvC;IAEA,MAAMK,iBAAiB,CAACC,OAA4C;YAChE,IAAI,CAAC,EAAE,EAAEA,KAAK,MAAM,CAAC,YAAY,EAAEA,KAAK,EAAE,EAAE;YAC5C,IAAI;QACR;IAEA,MAAMC,oBAAoB,CAACD,OAChB;YACH,SAAS,CAAC,EAAE,EAAEA,KAAK,MAAM,CAAC,YAAY,CAAC;YACvC,SAASA,KAAK,KAAK;YACnB,YAAYA,KAAK,MAAM;QAC3B;IAGJ,MAAME,oBAAiD;QACnD;YACI,OAAOR;QACX;QACA;YACI,OAAOG;QACX;QACA,MAAM,YAAW,EAAEG,IAAI,EAAE;YACrB,MAAMG,OAAO;gBACT,GAAGJ,eAAeC,KAAK;gBACvB,GAAGC,kBAAkBD,KAAK;YAC9B;YAEA,IAAI;gBACA,MAAMH,S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AmC;oBAC7E,cAAc,CAAC,EAAE,EAAEa,MAAM,MAAM,CAAC,YAAY,CAAC;oBAC7C,SAAS;wBACL,OAAO;oBACX;gBACJ;gBACAE,QAAQC,SAAS,GAAG,CAACC,CAAAA,OACVA,KAAK,IAAI;YAExB,EAAE,OAAOV,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;gBACV;YACJ;YAEA,MAAM,EAAEW,KAAK,EAAEC,QAAQ,EAAE,GAAGN;YAE5B,MAAMO,WAAWL,MAAM,MAAM,CAACE,CAAAA;gBAC1B,IAAII,MAAM,OAAO,CAACH,UAAU,CAACA,MAAM,QAAQ,CAACD,KAAK,EAAE,GAC/C,OAAO;gBAEX,IAAII,MAAM,OAAO,CAACF,WACd,OAAQF,AAAAA,CAAAA,KAAK,KAAK,IAAI,EAAC,EAAG,IAAI,CAACK,CAAAA,OAAQH,SAAS,QAAQ,CAACG;gBAE7D,OAAO;YACX;YAEA,OAAOC,UAAU;gBAAE,OAAOH;gBAAUN;YAAK;QAC7C;QACA,MAAM,YAAW,EAAEX,IAAI,EAAE;YACrB,MAAMG,OAAO;gBACT,GAAGJ,eAAeC,KAAK;gBACvB,GAAGC,kBAAkBD,KAAK;YAC9B;YAEA,IAAI;gBACA,MAAMH,SAAS,KAAK,CAAC,GAAG,CAAC;oBACrB,GAAGM,IAAI;oBACP,MAAM;oBACN,MAAMH;gBACV;gBACA,OAAOA;YACX,EAAE,OAAOI,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;wBAAMH;oBAAK;gBACvB;YACJ;QACJ;IACJ;IAEA,OAAOE;AACX"}
|
|
@@ -3,6 +3,11 @@ import type { DynamoDBDocument } from "@webiny/aws-sdk/client-dynamodb/index.js"
|
|
|
3
3
|
interface CreateKeysParams {
|
|
4
4
|
scopedKey: string;
|
|
5
5
|
}
|
|
6
|
+
interface CreateListKeysParams {
|
|
7
|
+
key: string;
|
|
8
|
+
scope: string;
|
|
9
|
+
collection: string;
|
|
10
|
+
}
|
|
6
11
|
export declare class KeyValueStoreDynamoTable<T extends GenericRecord> {
|
|
7
12
|
private readonly entity;
|
|
8
13
|
constructor(documentClient: DynamoDBDocument);
|
|
@@ -10,6 +15,25 @@ export declare class KeyValueStoreDynamoTable<T extends GenericRecord> {
|
|
|
10
15
|
PK: string;
|
|
11
16
|
SK: string;
|
|
12
17
|
};
|
|
18
|
+
/**
|
|
19
|
+
* GSI1 keys for a member of a collection. Each collection is its own GSI1 partition, sorted by
|
|
20
|
+
* key, so `list` is one Query on it. A record outside every collection gets no GSI1 keys at all
|
|
21
|
+
* and costs the index nothing. The primary key gives each record its own partition, which a
|
|
22
|
+
* Query cannot list.
|
|
23
|
+
*/
|
|
24
|
+
createListKeys({ key, scope, collection }: CreateListKeysParams): {
|
|
25
|
+
GSI1_PK: string;
|
|
26
|
+
GSI1_SK: string;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* The scope's length goes in front so the key reads back one way only: without it, scope `a#b`
|
|
30
|
+
* with collection `c` and scope `a` with collection `b#c` would share a partition, and a list
|
|
31
|
+
* in one scope would return another scope's records.
|
|
32
|
+
*/
|
|
33
|
+
createListPartitionKey(scope: string, collection: string): string;
|
|
34
|
+
/** Prefixed because DynamoDB rejects an empty string as an index key, and `""` is a valid key. */
|
|
35
|
+
createListSortKey(key: string): string;
|
|
36
|
+
parseListSortKey(sortKey: string): string;
|
|
13
37
|
getEntity(): import("@webiny/db-dynamodb").IEntity<import("@webiny/db-dynamodb").IGlobalEntityAttributes<T>>;
|
|
14
38
|
}
|
|
15
39
|
export {};
|
|
@@ -19,6 +19,21 @@ class KeyValueStoreDynamoTable {
|
|
|
19
19
|
SK: "A"
|
|
20
20
|
};
|
|
21
21
|
}
|
|
22
|
+
createListKeys({ key, scope, collection }) {
|
|
23
|
+
return {
|
|
24
|
+
GSI1_PK: this.createListPartitionKey(scope, collection),
|
|
25
|
+
GSI1_SK: this.createListSortKey(key)
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
createListPartitionKey(scope, collection) {
|
|
29
|
+
return `KV#COL#${scope.length}#${scope}#${collection}`;
|
|
30
|
+
}
|
|
31
|
+
createListSortKey(key) {
|
|
32
|
+
return `K#${key}`;
|
|
33
|
+
}
|
|
34
|
+
parseListSortKey(sortKey) {
|
|
35
|
+
return sortKey.slice(2);
|
|
36
|
+
}
|
|
22
37
|
getEntity() {
|
|
23
38
|
return this.entity;
|
|
24
39
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keyValueStore/KeyValueStoreDynamoTable.js","sources":["../../src/keyValueStore/KeyValueStoreDynamoTable.ts"],"sourcesContent":["import type { GenericRecord } from \"@webiny/api/types.js\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { createGlobalEntity, createTable, globalEntityAttributes } from \"@webiny/db-dynamodb\";\n\ninterface CreateKeysParams {\n scopedKey: string;\n}\n\nexport class KeyValueStoreDynamoTable<T extends GenericRecord> {\n private readonly entity;\n\n constructor(documentClient: DynamoDBDocument) {\n const table = createTable({\n name: process.env.DB_TABLE as string,\n documentClient\n });\n this.entity = createGlobalEntity<T>({\n name: \"KeyValueStore\",\n table: table.table,\n attributes: {\n ...globalEntityAttributes\n }\n });\n }\n\n createKeys({ scopedKey }: CreateKeysParams) {\n return {\n PK: `KV#${scopedKey}`,\n SK: `A`\n };\n }\n\n getEntity() {\n return this.entity;\n }\n}\n"],"names":["KeyValueStoreDynamoTable","documentClient","table","createTable","process","createGlobalEntity","globalEntityAttributes","scopedKey"],"mappings":";
|
|
1
|
+
{"version":3,"file":"keyValueStore/KeyValueStoreDynamoTable.js","sources":["../../src/keyValueStore/KeyValueStoreDynamoTable.ts"],"sourcesContent":["import type { GenericRecord } from \"@webiny/api/types.js\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { createGlobalEntity, createTable, globalEntityAttributes } from \"@webiny/db-dynamodb\";\n\ninterface CreateKeysParams {\n scopedKey: string;\n}\n\ninterface CreateListKeysParams {\n key: string;\n scope: string;\n collection: string;\n}\n\nexport class KeyValueStoreDynamoTable<T extends GenericRecord> {\n private readonly entity;\n\n constructor(documentClient: DynamoDBDocument) {\n const table = createTable({\n name: process.env.DB_TABLE as string,\n documentClient\n });\n this.entity = createGlobalEntity<T>({\n name: \"KeyValueStore\",\n table: table.table,\n attributes: {\n ...globalEntityAttributes\n }\n });\n }\n\n createKeys({ scopedKey }: CreateKeysParams) {\n return {\n PK: `KV#${scopedKey}`,\n SK: `A`\n };\n }\n\n /**\n * GSI1 keys for a member of a collection. Each collection is its own GSI1 partition, sorted by\n * key, so `list` is one Query on it. A record outside every collection gets no GSI1 keys at all\n * and costs the index nothing. The primary key gives each record its own partition, which a\n * Query cannot list.\n */\n createListKeys({ key, scope, collection }: CreateListKeysParams) {\n return {\n GSI1_PK: this.createListPartitionKey(scope, collection),\n GSI1_SK: this.createListSortKey(key)\n };\n }\n\n /**\n * The scope's length goes in front so the key reads back one way only: without it, scope `a#b`\n * with collection `c` and scope `a` with collection `b#c` would share a partition, and a list\n * in one scope would return another scope's records.\n */\n createListPartitionKey(scope: string, collection: string) {\n return `KV#COL#${scope.length}#${scope}#${collection}`;\n }\n\n /** Prefixed because DynamoDB rejects an empty string as an index key, and `\"\"` is a valid key. */\n createListSortKey(key: string) {\n return `K#${key}`;\n }\n\n parseListSortKey(sortKey: string) {\n return sortKey.slice(\"K#\".length);\n }\n\n getEntity() {\n return this.entity;\n }\n}\n"],"names":["KeyValueStoreDynamoTable","documentClient","table","createTable","process","createGlobalEntity","globalEntityAttributes","scopedKey","key","scope","collection","sortKey"],"mappings":";AAcO,MAAMA;IAGT,YAAYC,cAAgC,CAAE;QAC1C,MAAMC,QAAQC,YAAY;YACtB,MAAMC,QAAQ,GAAG,CAAC,QAAQ;YAC1BH;QACJ;QACA,IAAI,CAAC,MAAM,GAAGI,mBAAsB;YAChC,MAAM;YACN,OAAOH,MAAM,KAAK;YAClB,YAAY;gBACR,GAAGI,sBAAsB;YAC7B;QACJ;IACJ;IAEA,WAAW,EAAEC,SAAS,EAAoB,EAAE;QACxC,OAAO;YACH,IAAI,CAAC,GAAG,EAAEA,WAAW;YACrB,IAAI;QACR;IACJ;IAQA,eAAe,EAAEC,GAAG,EAAEC,KAAK,EAAEC,UAAU,EAAwB,EAAE;QAC7D,OAAO;YACH,SAAS,IAAI,CAAC,sBAAsB,CAACD,OAAOC;YAC5C,SAAS,IAAI,CAAC,iBAAiB,CAACF;QACpC;IACJ;IAOA,uBAAuBC,KAAa,EAAEC,UAAkB,EAAE;QACtD,OAAO,CAAC,OAAO,EAAED,MAAM,MAAM,CAAC,CAAC,EAAEA,MAAM,CAAC,EAAEC,YAAY;IAC1D;IAGA,kBAAkBF,GAAW,EAAE;QAC3B,OAAO,CAAC,EAAE,EAAEA,KAAK;IACrB;IAEA,iBAAiBG,OAAe,EAAE;QAC9B,OAAOA,QAAQ,KAAK,CAAC;IACzB;IAEA,YAAY;QACR,OAAO,IAAI,CAAC,MAAM;IACtB;AACJ"}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { DynamoDBDocument } from "@webiny/aws-sdk/client-dynamodb/index.js";
|
|
2
|
+
import type { IKeyValueStorageListParams } from "@webiny/api-core/features/keyValueStore/abstractions.js";
|
|
3
|
+
import type { IKeyValueStorageListResult } from "@webiny/api-core/features/keyValueStore/abstractions.js";
|
|
2
4
|
import type { IKeyValueStoreSetOptions } from "@webiny/api-core/features/keyValueStore/abstractions.js";
|
|
5
|
+
import type { IKeyValueDeleteOptions } from "@webiny/api-core/features/keyValueStore/abstractions.js";
|
|
3
6
|
interface KeyValueRecord {
|
|
4
7
|
key: string;
|
|
5
8
|
value: any;
|
|
@@ -8,10 +11,18 @@ interface KeyValueRecord {
|
|
|
8
11
|
export declare class KeyValueStoreStorageOperations {
|
|
9
12
|
private readonly table;
|
|
10
13
|
private readonly entity;
|
|
14
|
+
private readonly client;
|
|
11
15
|
constructor(dynamoDbClient: DynamoDBDocument);
|
|
12
16
|
private createScopedKey;
|
|
13
17
|
get(key: string, scope: string): Promise<KeyValueRecord | null>;
|
|
14
|
-
set(key: string, value: any, scope: string, options?: IKeyValueStoreSetOptions): Promise<
|
|
15
|
-
delete(key: string, scope: string): Promise<
|
|
18
|
+
set(key: string, value: any, scope: string, options?: IKeyValueStoreSetOptions): Promise<boolean>;
|
|
19
|
+
delete(key: string, scope: string, options?: IKeyValueDeleteOptions): Promise<boolean>;
|
|
20
|
+
list(params: IKeyValueStorageListParams): Promise<IKeyValueStorageListResult>;
|
|
21
|
+
/**
|
|
22
|
+
* A GSI query resumes from the full key of an item: the table's own PK and SK as well as the
|
|
23
|
+
* index's. All four follow from the scope, collection and key, so the item does not have to
|
|
24
|
+
* exist any more.
|
|
25
|
+
*/
|
|
26
|
+
private createStartKey;
|
|
16
27
|
}
|
|
17
28
|
export {};
|
|
@@ -1,9 +1,55 @@
|
|
|
1
1
|
import { WebinyError } from "@webiny/error";
|
|
2
2
|
import { KeyValueStoreDynamoTable } from "./KeyValueStoreDynamoTable.js";
|
|
3
|
+
const nowInSeconds = ()=>Math.floor(Date.now() / 1000);
|
|
4
|
+
const toEpochSeconds = (date)=>Math.ceil(date.getTime() / 1000);
|
|
5
|
+
const isExpired = (expiresAt)=>{
|
|
6
|
+
const ttl = Number(expiresAt);
|
|
7
|
+
return Boolean(ttl) && ttl <= nowInSeconds();
|
|
8
|
+
};
|
|
9
|
+
const isConditionFailed = (error)=>error?.name === "ConditionalCheckFailedException";
|
|
10
|
+
const notExistsCondition = ()=>({
|
|
11
|
+
expression: "attribute_not_exists(#pk) OR #expiresAt <= :now",
|
|
12
|
+
names: {
|
|
13
|
+
"#pk": "PK",
|
|
14
|
+
"#expiresAt": "expiresAt"
|
|
15
|
+
},
|
|
16
|
+
values: {
|
|
17
|
+
":now": nowInSeconds()
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
const liveCondition = ()=>({
|
|
21
|
+
expression: "attribute_exists(#pk) AND (attribute_not_exists(#expiresAt) OR #expiresAt > :now)",
|
|
22
|
+
names: {
|
|
23
|
+
"#pk": "PK",
|
|
24
|
+
"#expiresAt": "expiresAt"
|
|
25
|
+
},
|
|
26
|
+
values: {
|
|
27
|
+
":now": nowInSeconds()
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
const liveValueCondition = (equals)=>({
|
|
31
|
+
expression: "#data.#value = :equals AND (attribute_not_exists(#expiresAt) OR #expiresAt > :now)",
|
|
32
|
+
names: {
|
|
33
|
+
"#data": "data",
|
|
34
|
+
"#value": "value",
|
|
35
|
+
"#expiresAt": "expiresAt"
|
|
36
|
+
},
|
|
37
|
+
values: {
|
|
38
|
+
":equals": equals,
|
|
39
|
+
":now": nowInSeconds()
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
const toCondition = (condition)=>{
|
|
43
|
+
if (!condition) return;
|
|
44
|
+
if (void 0 !== condition.equals) return liveValueCondition(condition.equals);
|
|
45
|
+
if (condition.exists) return liveCondition();
|
|
46
|
+
return notExistsCondition();
|
|
47
|
+
};
|
|
3
48
|
class KeyValueStoreStorageOperations {
|
|
4
49
|
constructor(dynamoDbClient){
|
|
5
50
|
this.table = new KeyValueStoreDynamoTable(dynamoDbClient);
|
|
6
51
|
this.entity = this.table.getEntity();
|
|
52
|
+
this.client = dynamoDbClient;
|
|
7
53
|
}
|
|
8
54
|
createScopedKey(key, scope) {
|
|
9
55
|
return `${scope}:${key}`;
|
|
@@ -15,8 +61,7 @@ class KeyValueStoreStorageOperations {
|
|
|
15
61
|
scopedKey
|
|
16
62
|
}));
|
|
17
63
|
if (!entry) return null;
|
|
18
|
-
|
|
19
|
-
if (ttl && ttl <= Math.floor(Date.now() / 1000)) return null;
|
|
64
|
+
if (isExpired(entry.expiresAt)) return null;
|
|
20
65
|
return {
|
|
21
66
|
key,
|
|
22
67
|
value: entry.data.value,
|
|
@@ -39,17 +84,48 @@ class KeyValueStoreStorageOperations {
|
|
|
39
84
|
const keys = this.table.createKeys({
|
|
40
85
|
scopedKey
|
|
41
86
|
});
|
|
42
|
-
|
|
87
|
+
const item = {
|
|
43
88
|
...keys,
|
|
44
89
|
TYPE: "KeyValueStore",
|
|
45
|
-
expiresAt: options?.expiresAt ?
|
|
90
|
+
expiresAt: options?.expiresAt ? toEpochSeconds(options.expiresAt) : void 0,
|
|
46
91
|
data: {
|
|
47
92
|
key,
|
|
48
93
|
value,
|
|
49
94
|
scope
|
|
50
95
|
}
|
|
96
|
+
};
|
|
97
|
+
const collection = options?.collection;
|
|
98
|
+
if (collection) {
|
|
99
|
+
const listKeys = this.table.createListKeys({
|
|
100
|
+
key,
|
|
101
|
+
scope,
|
|
102
|
+
collection
|
|
103
|
+
});
|
|
104
|
+
Object.assign(item, listKeys);
|
|
105
|
+
}
|
|
106
|
+
const condition = toCondition(options?.condition);
|
|
107
|
+
if (!condition) {
|
|
108
|
+
await this.entity.put(item);
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
const params = this.entity.entity.putParams(item, {
|
|
112
|
+
strictSchemaCheck: false
|
|
113
|
+
});
|
|
114
|
+
await this.client.put({
|
|
115
|
+
...params,
|
|
116
|
+
ConditionExpression: condition.expression,
|
|
117
|
+
ExpressionAttributeNames: {
|
|
118
|
+
...params.ExpressionAttributeNames,
|
|
119
|
+
...condition.names
|
|
120
|
+
},
|
|
121
|
+
ExpressionAttributeValues: {
|
|
122
|
+
...params.ExpressionAttributeValues,
|
|
123
|
+
...condition.values
|
|
124
|
+
}
|
|
51
125
|
});
|
|
126
|
+
return true;
|
|
52
127
|
} catch (err) {
|
|
128
|
+
if (isConditionFailed(err)) return false;
|
|
53
129
|
throw WebinyError.from(err, {
|
|
54
130
|
message: "Could not set key-value record.",
|
|
55
131
|
code: "SET_KEY_VALUE_ERROR",
|
|
@@ -60,13 +136,33 @@ class KeyValueStoreStorageOperations {
|
|
|
60
136
|
});
|
|
61
137
|
}
|
|
62
138
|
}
|
|
63
|
-
async delete(key, scope) {
|
|
139
|
+
async delete(key, scope, options) {
|
|
64
140
|
try {
|
|
65
141
|
const scopedKey = this.createScopedKey(key, scope);
|
|
66
|
-
|
|
142
|
+
const keys = this.table.createKeys({
|
|
67
143
|
scopedKey
|
|
68
|
-
})
|
|
144
|
+
});
|
|
145
|
+
const condition = toCondition(options?.condition);
|
|
146
|
+
if (!condition) {
|
|
147
|
+
await this.entity.delete(keys);
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
const params = this.entity.entity.deleteParams(keys);
|
|
151
|
+
await this.client.delete({
|
|
152
|
+
...params,
|
|
153
|
+
ConditionExpression: condition.expression,
|
|
154
|
+
ExpressionAttributeNames: {
|
|
155
|
+
...params.ExpressionAttributeNames,
|
|
156
|
+
...condition.names
|
|
157
|
+
},
|
|
158
|
+
ExpressionAttributeValues: {
|
|
159
|
+
...params.ExpressionAttributeValues,
|
|
160
|
+
...condition.values
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
return true;
|
|
69
164
|
} catch (err) {
|
|
165
|
+
if (isConditionFailed(err)) return false;
|
|
70
166
|
throw WebinyError.from(err, {
|
|
71
167
|
message: "Could not delete key-value record.",
|
|
72
168
|
code: "DELETE_KEY_VALUE_ERROR",
|
|
@@ -77,6 +173,61 @@ class KeyValueStoreStorageOperations {
|
|
|
77
173
|
});
|
|
78
174
|
}
|
|
79
175
|
}
|
|
176
|
+
async list(params) {
|
|
177
|
+
const { collection, scope, limit, reverse, after } = params;
|
|
178
|
+
try {
|
|
179
|
+
const partitionKey = this.table.createListPartitionKey(scope, collection);
|
|
180
|
+
let startKey;
|
|
181
|
+
if (void 0 !== after) startKey = this.createStartKey({
|
|
182
|
+
key: after,
|
|
183
|
+
scope,
|
|
184
|
+
collection
|
|
185
|
+
});
|
|
186
|
+
const { items, lastEvaluatedKey } = await this.entity.queryPerPage({
|
|
187
|
+
partitionKey,
|
|
188
|
+
options: {
|
|
189
|
+
index: "GSI1",
|
|
190
|
+
limit: limit + 1,
|
|
191
|
+
reverse,
|
|
192
|
+
startKey
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
const page = items.slice(0, limit);
|
|
196
|
+
const keyOf = (item)=>item.data.key ?? "";
|
|
197
|
+
let lastKey = null;
|
|
198
|
+
if (items.length > limit) lastKey = keyOf(page[page.length - 1]);
|
|
199
|
+
else if (lastEvaluatedKey) lastKey = this.table.parseListSortKey(lastEvaluatedKey.GSI1_SK);
|
|
200
|
+
return {
|
|
201
|
+
items: page.filter((item)=>!isExpired(item.expiresAt)).map((item)=>({
|
|
202
|
+
key: keyOf(item),
|
|
203
|
+
value: item.data.value
|
|
204
|
+
})),
|
|
205
|
+
lastKey
|
|
206
|
+
};
|
|
207
|
+
} catch (err) {
|
|
208
|
+
throw WebinyError.from(err, {
|
|
209
|
+
message: "Could not list key-value records.",
|
|
210
|
+
code: "LIST_KEY_VALUE_ERROR",
|
|
211
|
+
data: {
|
|
212
|
+
collection,
|
|
213
|
+
scope,
|
|
214
|
+
after
|
|
215
|
+
}
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
createStartKey(params) {
|
|
220
|
+
const { key, scope } = params;
|
|
221
|
+
const scopedKey = this.createScopedKey(key, scope);
|
|
222
|
+
const tableKeys = this.table.createKeys({
|
|
223
|
+
scopedKey
|
|
224
|
+
});
|
|
225
|
+
const listKeys = this.table.createListKeys(params);
|
|
226
|
+
return {
|
|
227
|
+
...tableKeys,
|
|
228
|
+
...listKeys
|
|
229
|
+
};
|
|
230
|
+
}
|
|
80
231
|
}
|
|
81
232
|
export { KeyValueStoreStorageOperations };
|
|
82
233
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keyValueStore/KeyValueStoreStorageOperations.js","sources":["../../src/keyValueStore/KeyValueStoreStorageOperations.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { WebinyError } from \"@webiny/error\";\nimport type { IKeyValueStoreSetOptions } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport { KeyValueStoreDynamoTable } from \"./KeyValueStoreDynamoTable.js\";\n\ninterface KeyValueRecord {\n key: string;\n value: any;\n scope: string;\n}\n\nexport class KeyValueStoreStorageOperations {\n private readonly table;\n private readonly entity;\n\n constructor(dynamoDbClient: DynamoDBDocument) {\n this.table = new KeyValueStoreDynamoTable<KeyValueRecord>(dynamoDbClient);\n this.entity = this.table.getEntity();\n }\n\n private createScopedKey(key: string, scope: string): string {\n return `${scope}:${key}`;\n }\n\n async get(key: string, scope: string): Promise<KeyValueRecord | null> {\n try {\n const scopedKey = this.createScopedKey(key, scope);\n const entry = await this.entity.get(this.table.createKeys({ scopedKey }));\n\n if (!entry) {\n return null;\n }\n\n const ttl = Number(entry.expiresAt);\n if (ttl && ttl <= Math.floor(Date.now() / 1000)) {\n return null;\n }\n\n return {\n key,\n value: entry.data.value,\n scope: entry.data.scope\n };\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not get key-value record.\",\n code: \"GET_KEY_VALUE_ERROR\",\n data: { key, scope }\n });\n }\n }\n\n async set(\n key: string,\n value: any,\n scope: string,\n options?: IKeyValueStoreSetOptions\n ): Promise<void> {\n try {\n const scopedKey = this.createScopedKey(key, scope);\n const keys = this.table.createKeys({ scopedKey });\n\n await this.entity.put({\n ...keys,\n TYPE: \"KeyValueStore\",\n expiresAt: options?.expiresAt\n ? Math.floor(options.expiresAt.getTime() / 1000)\n : undefined,\n data: {\n key,\n value,\n scope\n }\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not set key-value record.\",\n code: \"SET_KEY_VALUE_ERROR\",\n data: { key, scope }\n });\n }\n }\n\n async delete(key: string, scope: string): Promise<void> {\n try {\n const scopedKey = this.createScopedKey(key, scope);\n await this.entity.delete(this.table.createKeys({ scopedKey }));\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete key-value record.\",\n code: \"DELETE_KEY_VALUE_ERROR\",\n data: { key, scope }\n });\n }\n }\n}\n"],"names":["KeyValueStoreStorageOperations","dynamoDbClient","KeyValueStoreDynamoTable","key","scope","scopedKey","entry","ttl","Number","Math","Date","err","WebinyError","value","options","keys","undefined"],"mappings":";;AAWO,MAAMA;IAIT,YAAYC,cAAgC,CAAE;QAC1C,IAAI,CAAC,KAAK,GAAG,IAAIC,yBAAyCD;QAC1D,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS;IACtC;IAEQ,gBAAgBE,GAAW,EAAEC,KAAa,EAAU;QACxD,OAAO,GAAGA,MAAM,CAAC,EAAED,KAAK;IAC5B;IAEA,MAAM,IAAIA,GAAW,EAAEC,KAAa,EAAkC;QAClE,IAAI;YACA,MAAMC,YAAY,IAAI,CAAC,eAAe,CAACF,KAAKC;YAC5C,MAAME,QAAQ,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC;gBAAED;YAAU;YAEtE,IAAI,CAACC,OACD,OAAO;YAGX,MAAMC,MAAMC,OAAOF,MAAM,SAAS;YAClC,IAAIC,OAAOA,OAAOE,KAAK,KAAK,CAACC,KAAK,GAAG,KAAK,OACtC,OAAO;YAGX,OAAO;gBACHP;gBACA,OAAOG,MAAM,IAAI,CAAC,KAAK;gBACvB,OAAOA,MAAM,IAAI,CAAC,KAAK;YAC3B;QACJ,EAAE,OAAOK,KAAK;YACV,MAAMC,YAAY,IAAI,CAACD,KAAK;gBACxB,SAAS;gBACT,MAAM;gBACN,MAAM;oBAAER;oBAAKC;gBAAM;YACvB;QACJ;IACJ;IAEA,MAAM,IACFD,GAAW,EACXU,KAAU,EACVT,KAAa,EACbU,OAAkC,EACrB;QACb,IAAI;YACA,MAAMT,YAAY,IAAI,CAAC,eAAe,CAACF,KAAKC;YAC5C,MAAMW,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC;gBAAEV;YAAU;YAE/C,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC;gBAClB,GAAGU,IAAI;gBACP,MAAM;gBACN,WAAWD,SAAS,YACdL,KAAK,KAAK,CAACK,QAAQ,SAAS,CAAC,OAAO,KAAK,QACzCE;gBACN,MAAM;oBACFb;oBACAU;oBACAT;gBACJ;YACJ;QACJ,EAAE,OAAOO,KAAK;YACV,MAAMC,YAAY,IAAI,CAACD,KAAK;gBACxB,SAAS;gBACT,MAAM;gBACN,MAAM;oBAAER;oBAAKC;gBAAM;YACvB;QACJ;IACJ;IAEA,MAAM,OAAOD,GAAW,EAAEC,KAAa,EAAiB;QACpD,IAAI;YACA,MAAMC,YAAY,IAAI,CAAC,eAAe,CAACF,KAAKC;YAC5C,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC;gBAAEC;YAAU;QAC/D,EAAE,OAAOM,KAAK;YACV,MAAMC,YAAY,IAAI,CAACD,KAAK;gBACxB,SAAS;gBACT,MAAM;gBACN,MAAM;oBAAER;oBAAKC;gBAAM;YACvB;QACJ;IACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"keyValueStore/KeyValueStoreStorageOperations.js","sources":["../../src/keyValueStore/KeyValueStoreStorageOperations.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { WebinyError } from \"@webiny/error\";\nimport type { IKeyValueStorageListParams } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport type { IKeyValueStorageListResult } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport type { IKeyValueStoreSetOptions } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport type { IKeyValueDeleteOptions } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport type { IKeyValueWriteCondition } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport type { KeyValueComparable } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport type { IGlobalEntityAttributes } from \"@webiny/db-dynamodb\";\nimport { KeyValueStoreDynamoTable } from \"./KeyValueStoreDynamoTable.js\";\n\ninterface KeyValueRecord {\n key: string;\n value: any;\n scope: string;\n}\n\nconst nowInSeconds = (): number => {\n return Math.floor(Date.now() / 1000);\n};\n\n/*\n * DynamoDB keeps `expiresAt` in whole seconds. Rounded up, a record never counts as expired before\n * the time it was given; rounded down, an `exists: false` write could take it over up to a\n * second early.\n */\nconst toEpochSeconds = (date: Date): number => {\n return Math.ceil(date.getTime() / 1000);\n};\n\nconst isExpired = (expiresAt: unknown): boolean => {\n const ttl = Number(expiresAt);\n return Boolean(ttl) && ttl <= nowInSeconds();\n};\n\nconst isConditionFailed = (error: unknown): boolean => {\n return (error as { name?: unknown })?.name === \"ConditionalCheckFailedException\";\n};\n\ninterface ICondition {\n expression: string;\n names: Record<string, string>;\n values: Record<string, unknown>;\n}\n\n/*\n * DynamoDB's TTL deletes expired items late, so each condition checks the time itself. DynamoDB\n * rejects a name or value the expression does not use, so each condition carries exactly its own.\n */\nconst notExistsCondition = (): ICondition => {\n return {\n expression: \"attribute_not_exists(#pk) OR #expiresAt <= :now\",\n names: { \"#pk\": \"PK\", \"#expiresAt\": \"expiresAt\" },\n values: { \":now\": nowInSeconds() }\n };\n};\n\nconst liveCondition = (): ICondition => {\n return {\n expression:\n \"attribute_exists(#pk) AND (attribute_not_exists(#expiresAt) OR #expiresAt > :now)\",\n names: { \"#pk\": \"PK\", \"#expiresAt\": \"expiresAt\" },\n values: { \":now\": nowInSeconds() }\n };\n};\n\nconst liveValueCondition = (equals: KeyValueComparable): ICondition => {\n return {\n expression:\n \"#data.#value = :equals AND (attribute_not_exists(#expiresAt) OR #expiresAt > :now)\",\n names: { \"#data\": \"data\", \"#value\": \"value\", \"#expiresAt\": \"expiresAt\" },\n values: { \":equals\": equals, \":now\": nowInSeconds() }\n };\n};\n\nconst toCondition = (condition: IKeyValueWriteCondition | undefined): ICondition | undefined => {\n if (!condition) {\n return undefined;\n }\n if (condition.equals !== undefined) {\n return liveValueCondition(condition.equals);\n }\n if (condition.exists) {\n return liveCondition();\n }\n return notExistsCondition();\n};\n\nexport class KeyValueStoreStorageOperations {\n private readonly table;\n private readonly entity;\n private readonly client;\n\n constructor(dynamoDbClient: DynamoDBDocument) {\n this.table = new KeyValueStoreDynamoTable<KeyValueRecord>(dynamoDbClient);\n this.entity = this.table.getEntity();\n this.client = dynamoDbClient;\n }\n\n private createScopedKey(key: string, scope: string): string {\n return `${scope}:${key}`;\n }\n\n async get(key: string, scope: string): Promise<KeyValueRecord | null> {\n try {\n const scopedKey = this.createScopedKey(key, scope);\n const entry = await this.entity.get(this.table.createKeys({ scopedKey }));\n\n if (!entry) {\n return null;\n }\n\n if (isExpired(entry.expiresAt)) {\n return null;\n }\n\n return {\n key,\n value: entry.data.value,\n scope: entry.data.scope\n };\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not get key-value record.\",\n code: \"GET_KEY_VALUE_ERROR\",\n data: { key, scope }\n });\n }\n }\n\n async set(\n key: string,\n value: any,\n scope: string,\n options?: IKeyValueStoreSetOptions\n ): Promise<boolean> {\n try {\n const scopedKey = this.createScopedKey(key, scope);\n const keys = this.table.createKeys({ scopedKey });\n\n const item: IGlobalEntityAttributes<KeyValueRecord> = {\n ...keys,\n TYPE: \"KeyValueStore\",\n expiresAt: options?.expiresAt ? toEpochSeconds(options.expiresAt) : undefined,\n data: {\n key,\n value,\n scope\n }\n };\n\n /*\n * A put replaces the whole item, so a write without a collection also drops GSI1 keys\n * an earlier write gave it, which takes the record out of that collection.\n */\n const collection = options?.collection;\n if (collection) {\n const listKeys = this.table.createListKeys({ key, scope, collection });\n Object.assign(item, listKeys);\n }\n\n const condition = toCondition(options?.condition);\n if (!condition) {\n await this.entity.put(item);\n return true;\n }\n\n // The entity builds the put it would send itself, so the stored item is the same.\n const params = this.entity.entity.putParams(item, { strictSchemaCheck: false });\n await this.client.put({\n ...params,\n ConditionExpression: condition.expression,\n ExpressionAttributeNames: {\n ...params.ExpressionAttributeNames,\n ...condition.names\n },\n ExpressionAttributeValues: {\n ...params.ExpressionAttributeValues,\n ...condition.values\n }\n });\n return true;\n } catch (err) {\n if (isConditionFailed(err)) {\n return false;\n }\n throw WebinyError.from(err, {\n message: \"Could not set key-value record.\",\n code: \"SET_KEY_VALUE_ERROR\",\n data: { key, scope }\n });\n }\n }\n\n async delete(key: string, scope: string, options?: IKeyValueDeleteOptions): Promise<boolean> {\n try {\n const scopedKey = this.createScopedKey(key, scope);\n const keys = this.table.createKeys({ scopedKey });\n const condition = toCondition(options?.condition);\n if (!condition) {\n await this.entity.delete(keys);\n return true;\n }\n\n const params = this.entity.entity.deleteParams(keys);\n await this.client.delete({\n ...params,\n ConditionExpression: condition.expression,\n ExpressionAttributeNames: {\n ...params.ExpressionAttributeNames,\n ...condition.names\n },\n ExpressionAttributeValues: {\n ...params.ExpressionAttributeValues,\n ...condition.values\n }\n });\n return true;\n } catch (err) {\n if (isConditionFailed(err)) {\n return false;\n }\n throw WebinyError.from(err, {\n message: \"Could not delete key-value record.\",\n code: \"DELETE_KEY_VALUE_ERROR\",\n data: { key, scope }\n });\n }\n }\n\n async list(params: IKeyValueStorageListParams): Promise<IKeyValueStorageListResult> {\n const { collection, scope, limit, reverse, after } = params;\n try {\n const partitionKey = this.table.createListPartitionKey(scope, collection);\n\n let startKey: Record<string, string> | undefined;\n if (after !== undefined) {\n startKey = this.createStartKey({ key: after, scope, collection });\n }\n\n // One extra record tells whether another page exists without a second, empty read.\n const { items, lastEvaluatedKey } = await this.entity.queryPerPage<\n IGlobalEntityAttributes<KeyValueRecord>\n >({\n partitionKey,\n options: {\n index: \"GSI1\",\n limit: limit + 1,\n reverse,\n startKey\n }\n });\n\n const page = items.slice(0, limit);\n // A key DynamoDB holds as \"\" comes back as null from the entity.\n const keyOf = (item: (typeof items)[number]) => item.data.key ?? \"\";\n\n let lastKey: string | null = null;\n if (items.length > limit) {\n lastKey = keyOf(page[page.length - 1]);\n } else if (lastEvaluatedKey) {\n // The 1 MB read limit cut the page short of `limit`.\n lastKey = this.table.parseListSortKey(lastEvaluatedKey.GSI1_SK as string);\n }\n\n return {\n items: page\n .filter(item => !isExpired(item.expiresAt))\n .map(item => ({ key: keyOf(item), value: item.data.value })),\n lastKey\n };\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list key-value records.\",\n code: \"LIST_KEY_VALUE_ERROR\",\n data: { collection, scope, after }\n });\n }\n }\n\n /**\n * A GSI query resumes from the full key of an item: the table's own PK and SK as well as the\n * index's. All four follow from the scope, collection and key, so the item does not have to\n * exist any more.\n */\n private createStartKey(params: { key: string; scope: string; collection: string }) {\n const { key, scope } = params;\n const scopedKey = this.createScopedKey(key, scope);\n const tableKeys = this.table.createKeys({ scopedKey });\n const listKeys = this.table.createListKeys(params);\n\n return { ...tableKeys, ...listKeys };\n }\n}\n"],"names":["nowInSeconds","Math","Date","toEpochSeconds","date","isExpired","expiresAt","ttl","Number","Boolean","isConditionFailed","error","notExistsCondition","liveCondition","liveValueCondition","equals","toCondition","condition","undefined","KeyValueStoreStorageOperations","dynamoDbClient","KeyValueStoreDynamoTable","key","scope","scopedKey","entry","err","WebinyError","value","options","keys","item","collection","listKeys","Object","params","limit","reverse","after","partitionKey","startKey","items","lastEvaluatedKey","page","keyOf","lastKey","tableKeys"],"mappings":";;AAiBA,MAAMA,eAAe,IACVC,KAAK,KAAK,CAACC,KAAK,GAAG,KAAK;AAQnC,MAAMC,iBAAiB,CAACC,OACbH,KAAK,IAAI,CAACG,KAAK,OAAO,KAAK;AAGtC,MAAMC,YAAY,CAACC;IACf,MAAMC,MAAMC,OAAOF;IACnB,OAAOG,QAAQF,QAAQA,OAAOP;AAClC;AAEA,MAAMU,oBAAoB,CAACC,QACfA,OAA8B,SAAS;AAanD,MAAMC,qBAAqB,IAChB;QACH,YAAY;QACZ,OAAO;YAAE,OAAO;YAAM,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
|
"name": "@webiny/api-core-ddb",
|
|
3
|
-
"version": "6.6.0-alpha.
|
|
3
|
+
"version": "6.6.0-alpha.10",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": "./index.js",
|
|
@@ -21,20 +21,20 @@
|
|
|
21
21
|
"author": "Webiny Ltd.",
|
|
22
22
|
"license": "MIT",
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@webiny/api": "6.6.0-alpha.
|
|
25
|
-
"@webiny/api-core": "6.6.0-alpha.
|
|
26
|
-
"@webiny/aws-sdk": "6.6.0-alpha.
|
|
27
|
-
"@webiny/db-dynamodb": "6.6.0-alpha.
|
|
28
|
-
"@webiny/error": "6.6.0-alpha.
|
|
29
|
-
"@webiny/feature": "6.6.0-alpha.
|
|
24
|
+
"@webiny/api": "6.6.0-alpha.10",
|
|
25
|
+
"@webiny/api-core": "6.6.0-alpha.10",
|
|
26
|
+
"@webiny/aws-sdk": "6.6.0-alpha.10",
|
|
27
|
+
"@webiny/db-dynamodb": "6.6.0-alpha.10",
|
|
28
|
+
"@webiny/error": "6.6.0-alpha.10",
|
|
29
|
+
"@webiny/feature": "6.6.0-alpha.10"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
|
-
"@webiny/api": "6.6.0-alpha.
|
|
33
|
-
"@webiny/build-tools": "6.6.0-alpha.
|
|
34
|
-
"@webiny/project-utils": "6.6.0-alpha.0",
|
|
32
|
+
"@webiny/api": "6.6.0-alpha.10",
|
|
33
|
+
"@webiny/build-tools": "6.6.0-alpha.10",
|
|
35
34
|
"jest-dynalite": "3.6.1",
|
|
36
35
|
"rimraf": "6.1.3",
|
|
37
|
-
"typescript": "7.0.2"
|
|
36
|
+
"typescript": "7.0.2",
|
|
37
|
+
"vitest": "5.0.5"
|
|
38
38
|
},
|
|
39
39
|
"publishConfig": {
|
|
40
40
|
"access": "public"
|