@webiny/api-core-ddb 0.0.0-unstable.0d717d18dd → 0.0.0-unstable.292eb6dc15

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.
@@ -1,11 +1,18 @@
1
1
  import { createFeature } from "@webiny/feature/api";
2
- import { ApiCoreStorageOperationsFactory } from "@webiny/api-core";
2
+ import { ApiCoreStorageOperationsFactory, TenancyStorageOperationsFactory } from "@webiny/api-core";
3
3
  import { createApiCoreDdb } from "./createApiCoreDdb.js";
4
+ import { createStorageOperations } from "./tenancy/index.js";
4
5
  const ApiCoreDdbFeature = createFeature({
5
6
  name: "ApiCoreDdb",
6
7
  register (container, { documentClient }) {
7
8
  container.registerInstance(ApiCoreStorageOperationsFactory, {
8
- create: ()=>createApiCoreDdb({
9
+ create: ({ scopeTenant })=>createApiCoreDdb({
10
+ documentClient,
11
+ scopeTenant
12
+ })
13
+ });
14
+ container.registerInstance(TenancyStorageOperationsFactory, {
15
+ create: ()=>createStorageOperations({
9
16
  documentClient
10
17
  })
11
18
  });
@@ -1 +1 @@
1
- {"version":3,"file":"ApiCoreDdbFeature.js","sources":["../src/ApiCoreDdbFeature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { ApiCoreStorageOperationsFactory } from \"@webiny/api-core\";\nimport { createApiCoreDdb } from \"./createApiCoreDdb.js\";\n\nexport interface ApiCoreDdbConfig {\n documentClient: DynamoDBDocument;\n}\n\n/**\n * Registers the DynamoDB implementation of ApiCoreStorageOperationsFactory. ApiCoreFeature.register\n * resolves + builds it. Mirrors HeadlessCmsDdbFeature.\n */\nexport const ApiCoreDdbFeature = createFeature<ApiCoreDdbConfig>({\n name: \"ApiCoreDdb\",\n register(container, { documentClient }) {\n container.registerInstance(ApiCoreStorageOperationsFactory, {\n create: () => createApiCoreDdb({ documentClient })\n });\n }\n});\n"],"names":["ApiCoreDdbFeature","createFeature","container","documentClient","ApiCoreStorageOperationsFactory","createApiCoreDdb"],"mappings":";;;AAaO,MAAMA,oBAAoBC,cAAgC;IAC7D,MAAM;IACN,UAASC,SAAS,EAAE,EAAEC,cAAc,EAAE;QAClCD,UAAU,gBAAgB,CAACE,iCAAiC;YACxD,QAAQ,IAAMC,iBAAiB;oBAAEF;gBAAe;QACpD;IACJ;AACJ"}
1
+ {"version":3,"file":"ApiCoreDdbFeature.js","sources":["../src/ApiCoreDdbFeature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { ApiCoreStorageOperationsFactory, TenancyStorageOperationsFactory } from \"@webiny/api-core\";\nimport { createApiCoreDdb } from \"./createApiCoreDdb.js\";\nimport { createStorageOperations as createTenancyStorageOperations } from \"./tenancy/index.js\";\n\nexport interface ApiCoreDdbConfig {\n documentClient: DynamoDBDocument;\n}\n\n/**\n * Registers the DynamoDB implementation of ApiCoreStorageOperationsFactory. ApiCoreFeature.register\n * resolves + builds it. Mirrors HeadlessCmsDdbFeature.\n */\nexport const ApiCoreDdbFeature = createFeature<ApiCoreDdbConfig>({\n name: \"ApiCoreDdb\",\n register(container, { documentClient }) {\n container.registerInstance(ApiCoreStorageOperationsFactory, {\n create: ({ scopeTenant }) => createApiCoreDdb({ documentClient, scopeTenant })\n });\n // The tenant registry on its own: the request container reads the request's tenant from it.\n container.registerInstance(TenancyStorageOperationsFactory, {\n create: () => createTenancyStorageOperations({ documentClient })\n });\n }\n});\n"],"names":["ApiCoreDdbFeature","createFeature","container","documentClient","ApiCoreStorageOperationsFactory","scopeTenant","createApiCoreDdb","TenancyStorageOperationsFactory","createTenancyStorageOperations"],"mappings":";;;;AAcO,MAAMA,oBAAoBC,cAAgC;IAC7D,MAAM;IACN,UAASC,SAAS,EAAE,EAAEC,cAAc,EAAE;QAClCD,UAAU,gBAAgB,CAACE,iCAAiC;YACxD,QAAQ,CAAC,EAAEC,WAAW,EAAE,GAAKC,iBAAiB;oBAAEH;oBAAgBE;gBAAY;QAChF;QAEAH,UAAU,gBAAgB,CAACK,iCAAiC;YACxD,QAAQ,IAAMC,wBAA+B;oBAAEL;gBAAe;QAClE;IACJ;AACJ"}
@@ -2,7 +2,11 @@ import error from "@webiny/error";
2
2
  import { createTable, sortItems } from "@webiny/db-dynamodb";
3
3
  import { createUserEntity } from "./definitions/entities.js";
4
4
  const createStorageOperations = (params)=>{
5
- const { table: tableName, documentClient } = params;
5
+ const { table: tableName, documentClient, scopeTenant } = params;
6
+ const inScope = (user)=>({
7
+ ...user,
8
+ tenant: scopeTenant.getId()
9
+ });
6
10
  const table = createTable({
7
11
  name: tableName || process.env.DB_TABLE,
8
12
  documentClient
@@ -14,9 +18,12 @@ const createStorageOperations = (params)=>{
14
18
  PK: `T#${user.tenant}#ADMIN_USER#${user.id}`,
15
19
  SK: "A"
16
20
  });
21
+ const createUserIndexPartitionKey = (id)=>`ADMIN_USER#${id}`;
17
22
  const createUserGSIKeys = (user)=>({
18
23
  GSI1_PK: `T#${user.tenant}#ADMIN_USERS`,
19
24
  GSI1_SK: user.email,
25
+ GSI2_PK: createUserIndexPartitionKey(user.id),
26
+ GSI2_SK: `T#${user.tenant}`,
20
27
  GSI_TENANT: user.tenant
21
28
  });
22
29
  const storageOperations = {
@@ -26,7 +33,8 @@ const createStorageOperations = (params)=>{
26
33
  getEntities () {
27
34
  return entities;
28
35
  },
29
- async createUser ({ user }) {
36
+ async createUser (params) {
37
+ const user = inScope(params.user);
30
38
  const keys = {
31
39
  ...createUserKeys(user),
32
40
  ...createUserGSIKeys(user)
@@ -48,7 +56,8 @@ const createStorageOperations = (params)=>{
48
56
  });
49
57
  }
50
58
  },
51
- async deleteUser ({ user }) {
59
+ async deleteUser (params) {
60
+ const user = inScope(params.user);
52
61
  const keys = createUserKeys(user);
53
62
  try {
54
63
  await entities.users.delete(keys);
@@ -64,7 +73,8 @@ const createStorageOperations = (params)=>{
64
73
  }
65
74
  },
66
75
  async getUser (params) {
67
- const { where: { tenant, id, email } } = params;
76
+ const { where: { id, email } } = params;
77
+ const tenant = scopeTenant.getId();
68
78
  try {
69
79
  if (id) {
70
80
  const response = await entities.users.get(createUserKeys({
@@ -92,11 +102,55 @@ const createStorageOperations = (params)=>{
92
102
  });
93
103
  }
94
104
  },
105
+ async getUserAcrossTenants (params) {
106
+ const { id, tenants } = params;
107
+ if (0 === tenants.length) return [];
108
+ try {
109
+ const reader = entities.users.createEntityReader({
110
+ read: tenants.map((tenant)=>createUserKeys({
111
+ tenant,
112
+ id
113
+ }))
114
+ });
115
+ const items = await reader.execute();
116
+ return items.filter((item)=>!!item?.data).map((item)=>item.data);
117
+ } catch (err) {
118
+ throw error.from(err, {
119
+ message: "Could not load user across tenants.",
120
+ code: "GET_ADMIN_USER_ACROSS_TENANTS_ERROR",
121
+ data: {
122
+ id,
123
+ tenants
124
+ }
125
+ });
126
+ }
127
+ },
128
+ async listUserRecords (params) {
129
+ const { id } = params;
130
+ try {
131
+ const items = await entities.users.queryAll({
132
+ partitionKey: createUserIndexPartitionKey(id),
133
+ options: {
134
+ index: "GSI2"
135
+ }
136
+ });
137
+ return items.map((item)=>item.data);
138
+ } catch (err) {
139
+ throw error.from(err, {
140
+ message: "Could not list user records.",
141
+ code: "LIST_ADMIN_USER_RECORDS_ERROR",
142
+ data: {
143
+ id
144
+ }
145
+ });
146
+ }
147
+ },
95
148
  async listUsers ({ where, sort }) {
149
+ const tenant = scopeTenant.getId();
96
150
  let items;
97
151
  try {
98
152
  const ddbItems = await entities.users.queryAll({
99
- partitionKey: `T#${where.tenant}#ADMIN_USERS`,
153
+ partitionKey: `T#${tenant}#ADMIN_USERS`,
100
154
  options: {
101
155
  index: "GSI1"
102
156
  }
@@ -108,12 +162,19 @@ const createStorageOperations = (params)=>{
108
162
  code: "LIST_ADMIN_USERS_ERROR"
109
163
  });
110
164
  }
165
+ const { id_in, teams_in } = where;
166
+ const filtered = items.filter((item)=>{
167
+ if (Array.isArray(id_in) && !id_in.includes(item.id)) return false;
168
+ if (Array.isArray(teams_in)) return (item.teams || []).some((team)=>teams_in.includes(team));
169
+ return true;
170
+ });
111
171
  return sortItems({
112
- items,
172
+ items: filtered,
113
173
  sort
114
174
  });
115
175
  },
116
- async updateUser ({ user }) {
176
+ async updateUser (params) {
177
+ const user = inScope(params.user);
117
178
  const keys = {
118
179
  ...createUserKeys(user),
119
180
  ...createUserGSIKeys(user)
@@ -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,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,SAAS,KAAK,CAAC,GAAG,CAAC;oBACrB,GAAGM,IAAI;oBACP,MAAM;oBACN,MAAMH;gBACV;gBAEA,OAAOA;YACX,EAAE,OAAOI,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;oBAAK;gBACjB;YACJ;QACJ;QACA,MAAM,YAAW,EAAEH,IAAI,EAAE;YACrB,MAAMG,OAAOJ,eAAeC;YAE5B,IAAI;gBACA,MAAMH,SAAS,KAAK,CAAC,MAAM,CAACM;YAChC,EAAE,OAAOC,KAAK;gBACV,MA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,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"}
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 StorageOperationsGetUserAcrossTenantsParams,\n StorageOperationsGetUserParams,\n StorageOperationsListUserRecordsParams,\n StorageOperationsListUsersParams\n} from \"@webiny/api-core/types/users.js\";\n\nexport const createStorageOperations: CreateAdminUsersStorageOperations = params => {\n const { table: tableName, documentClient, scopeTenant } = params;\n\n /** The user with its scope's tenant, whatever tenant it carries. */\n const inScope = <T extends AdminUser>(user: T): T => {\n return { ...user, tenant: scopeTenant.getId() };\n };\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 createUserIndexPartitionKey = (id: string) => `ADMIN_USER#${id}`;\n\n const createUserGSIKeys = (user: AdminUser) => {\n return {\n GSI1_PK: `T#${user.tenant}#ADMIN_USERS`,\n GSI1_SK: user.email,\n // The user→tenant index: every tenant's record of one user, in one partition.\n GSI2_PK: createUserIndexPartitionKey(user.id),\n GSI2_SK: `T#${user.tenant}`,\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(params) {\n const user = inScope(params.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(params) {\n const user = inScope(params.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: { id, email }\n } = params;\n const tenant = scopeTenant.getId();\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 // Cross-tenant by design: one user's records in the given tenants, not the scope's tenant.\n async getUserAcrossTenants<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsGetUserAcrossTenantsParams\n ): Promise<TUser[]> {\n const { id, tenants } = params;\n if (tenants.length === 0) {\n return [];\n }\n\n try {\n // The batch reader splits the keys into chunks of 100 (the BatchGetItem limit).\n const reader = entities.users.createEntityReader({\n read: tenants.map(tenant => createUserKeys({ tenant, id }))\n });\n const items = await reader.execute();\n\n return items\n .filter(item => !!item?.data)\n .map(item => {\n return item.data as unknown as TUser;\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load user across tenants.\",\n code: \"GET_ADMIN_USER_ACROSS_TENANTS_ERROR\",\n data: { id, tenants }\n });\n }\n },\n // Cross-tenant by design: every tenant's record of one user.\n async listUserRecords<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsListUserRecordsParams\n ): Promise<TUser[]> {\n const { id } = params;\n\n try {\n const items = await entities.users.queryAll<IStandardEntityAttributes<TUser>>({\n partitionKey: createUserIndexPartitionKey(id),\n options: {\n index: \"GSI2\"\n }\n });\n\n return items.map(item => item.data as TUser);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list user records.\",\n code: \"LIST_ADMIN_USER_RECORDS_ERROR\",\n data: { id }\n });\n }\n },\n async listUsers<TUser extends AdminUser = AdminUser>({\n where,\n sort\n }: StorageOperationsListUsersParams) {\n const tenant = scopeTenant.getId();\n let items: TUser[];\n try {\n const ddbItems = await entities.users.queryAll<IStandardEntityAttributes<TUser>>({\n partitionKey: `T#${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(params) {\n const user = inScope(params.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","scopeTenant","inScope","user","table","createTable","process","entities","createUserEntity","createUserKeys","createUserIndexPartitionKey","id","createUserGSIKeys","storageOperations","keys","err","WebinyError","email","tenant","response","tenants","reader","items","item","where","sort","ddbItems","id_in","teams_in","filtered","Array","team","sortItems"],"mappings":";;;AAYO,MAAMA,0BAA6DC,CAAAA;IACtE,MAAM,EAAE,OAAOC,SAAS,EAAEC,cAAc,EAAEC,WAAW,EAAE,GAAGH;IAG1D,MAAMI,UAAU,CAAsBC,OAC3B;YAAE,GAAGA,IAAI;YAAE,QAAQF,YAAY,KAAK;QAAG;IAGlD,MAAMG,QAAQC,YAAY;QACtB,MAAMN,aAAcO,QAAQ,GAAG,CAAC,QAAQ;QACxCN;IACJ;IAEA,MAAMO,WAAW;QACb,OAAOC,iBAAiBJ,MAAM,KAAK;IACvC;IAEA,MAAMK,iBAAiB,CAACN,OAA4C;YAChE,IAAI,CAAC,EAAE,EAAEA,KAAK,MAAM,CAAC,YAAY,EAAEA,KAAK,EAAE,EAAE;YAC5C,IAAI;QACR;IAEA,MAAMO,8BAA8B,CAACC,KAAe,CAAC,WAAW,EAAEA,IAAI;IAEtE,MAAMC,oBAAoB,CAACT,OAChB;YACH,SAAS,CAAC,EAAE,EAAEA,KAAK,MAAM,CAAC,YAAY,CAAC;YACvC,SAASA,KAAK,KAAK;YAEnB,SAASO,4BAA4BP,KAAK,EAAE;YAC5C,SAAS,CAAC,EAAE,EAAEA,KAAK,MAAM,EAAE;YAC3B,YAAYA,KAAK,MAAM;QAC3B;IAGJ,MAAMU,oBAAiD;QACnD;YACI,OAAOT;QACX;QACA;YACI,OAAOG;QACX;QACA,MAAM,YAAWT,MAAM;YACnB,MAAMK,OAAOD,QAAQJ,OAAO,IAAI;YAChC,MAAMgB,OAAO;gBACT,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BACL,OAAO;oBACX;gBACJ;gBACAI,QAAQI,SAAS,GAAG,CAACH,CAAAA,OACVA,KAAK,IAAI;YAExB,EAAE,OAAOR,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;gBACV;YACJ;YAEA,MAAM,EAAEY,KAAK,EAAEC,QAAQ,EAAE,GAAGJ;YAE5B,MAAMK,WAAWP,MAAM,MAAM,CAACC,CAAAA;gBAC1B,IAAIO,MAAM,OAAO,CAACH,UAAU,CAACA,MAAM,QAAQ,CAACJ,KAAK,EAAE,GAC/C,OAAO;gBAEX,IAAIO,MAAM,OAAO,CAACF,WACd,OAAQL,AAAAA,CAAAA,KAAK,KAAK,IAAI,EAAC,EAAG,IAAI,CAACQ,CAAAA,OAAQH,SAAS,QAAQ,CAACG;gBAE7D,OAAO;YACX;YAEA,OAAOC,UAAU;gBAAE,OAAOH;gBAAUJ;YAAK;QAC7C;QACA,MAAM,YAAW3B,MAAM;YACnB,MAAMK,OAAOD,QAAQJ,OAAO,IAAI;YAChC,MAAMgB,OAAO;gBACT,GAAGL,eAAeN,KAAK;gBACvB,GAAGS,kBAAkBT,KAAK;YAC9B;YAEA,IAAI;gBACA,MAAMI,SAAS,KAAK,CAAC,GAAG,CAAC;oBACrB,GAAGO,IAAI;oBACP,MAAM;oBACN,MAAMX;gBACV;gBACA,OAAOA;YACX,EAAE,OAAOY,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;wBAAMX;oBAAK;gBACvB;YACJ;QACJ;IACJ;IAEA,OAAOU;AACX"}
@@ -2,12 +2,15 @@ import type { DynamoDBDocument } from "@webiny/aws-sdk/client-dynamodb/index.js"
2
2
  import type { AdminUsersStorageOperations as BaseAdminUsersStorageOperations } from "@webiny/api-core/types/users.js";
3
3
  import type { IAdminUserEntity } from "../adminUsers/definitions/types.js";
4
4
  import { ITable } from "@webiny/db-dynamodb";
5
+ import type { ScopeTenant } from "@webiny/api-core/features/tenancy/ScopeTenant/index.js";
5
6
  export declare enum ENTITIES {
6
7
  SYSTEM = "AdminUsers.System",
7
8
  USERS = "AdminUsers.User"
8
9
  }
9
10
  export interface ICreateAdminUsersStorageOperationsParams {
10
11
  documentClient: DynamoDBDocument;
12
+ /** The tenant the storage acts on: its scope's. Reading one user across tenants doesn't use it. */
13
+ scopeTenant: ScopeTenant.Interface;
11
14
  table?: string;
12
15
  }
13
16
  export interface CreateAdminUsersStorageOperations {
@@ -1 +1 @@
1
- {"version":3,"file":"adminUsers/types.js","sources":["../../src/adminUsers/types.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport type { AdminUsersStorageOperations as BaseAdminUsersStorageOperations } from \"@webiny/api-core/types/users.js\";\nimport type { IAdminUserEntity } from \"~/adminUsers/definitions/types.js\";\nimport { ITable } from \"@webiny/db-dynamodb\";\n\nexport enum ENTITIES {\n SYSTEM = \"AdminUsers.System\",\n USERS = \"AdminUsers.User\"\n}\n\nexport interface ICreateAdminUsersStorageOperationsParams {\n documentClient: DynamoDBDocument;\n table?: string;\n}\n\nexport interface CreateAdminUsersStorageOperations {\n (params: ICreateAdminUsersStorageOperationsParams): AdminUsersStorageOperations;\n}\n\nexport interface IAdminUsersGetEntitiesResponse {\n users: IAdminUserEntity;\n}\n\nexport interface AdminUsersStorageOperations extends BaseAdminUsersStorageOperations {\n getTable(): ITable;\n getEntities(): IAdminUsersGetEntitiesResponse;\n}\n"],"names":["ENTITIES"],"mappings":"AAKO,IAAKA,iBAAQA,WAAAA,GAAAA,SAARA,QAAQ;;;WAARA"}
1
+ {"version":3,"file":"adminUsers/types.js","sources":["../../src/adminUsers/types.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport type { AdminUsersStorageOperations as BaseAdminUsersStorageOperations } from \"@webiny/api-core/types/users.js\";\nimport type { IAdminUserEntity } from \"~/adminUsers/definitions/types.js\";\nimport { ITable } from \"@webiny/db-dynamodb\";\nimport type { ScopeTenant } from \"@webiny/api-core/features/tenancy/ScopeTenant/index.js\";\n\nexport enum ENTITIES {\n SYSTEM = \"AdminUsers.System\",\n USERS = \"AdminUsers.User\"\n}\n\nexport interface ICreateAdminUsersStorageOperationsParams {\n documentClient: DynamoDBDocument;\n /** The tenant the storage acts on: its scope's. Reading one user across tenants doesn't use it. */\n scopeTenant: ScopeTenant.Interface;\n table?: string;\n}\n\nexport interface CreateAdminUsersStorageOperations {\n (params: ICreateAdminUsersStorageOperationsParams): AdminUsersStorageOperations;\n}\n\nexport interface IAdminUsersGetEntitiesResponse {\n users: IAdminUserEntity;\n}\n\nexport interface AdminUsersStorageOperations extends BaseAdminUsersStorageOperations {\n getTable(): ITable;\n getEntities(): IAdminUsersGetEntitiesResponse;\n}\n"],"names":["ENTITIES"],"mappings":"AAMO,IAAKA,iBAAQA,WAAAA,GAAAA,SAAAA,QAAAA"}
@@ -1,7 +1,13 @@
1
1
  import type { ApiCoreStorageOperations } from "@webiny/api-core/types/core.js";
2
2
  import type { DynamoDBDocument } from "@webiny/aws-sdk/client-dynamodb/index.js";
3
+ import type { ScopeTenant } from "@webiny/api-core/features/tenancy/ScopeTenant/index.js";
3
4
  interface CreateApiCoreDdbParams {
4
5
  documentClient: DynamoDBDocument;
6
+ /**
7
+ * The tenant the storage acts on: its tenant scope's. The tenant records and the key-value store
8
+ * don't use it (the tenant registry is tenant-neutral, and the store is keyed by its own scope).
9
+ */
10
+ scopeTenant: ScopeTenant.Interface;
5
11
  }
6
- export declare const createApiCoreDdb: ({ documentClient }: CreateApiCoreDdbParams) => ApiCoreStorageOperations;
12
+ export declare const createApiCoreDdb: ({ documentClient, scopeTenant }: CreateApiCoreDdbParams) => ApiCoreStorageOperations;
7
13
  export {};
@@ -4,17 +4,19 @@ import { createStorageOperations as index_js_createStorageOperations } from "./t
4
4
  import { createStorageOperations as external_security_index_js_createStorageOperations } from "./security/index.js";
5
5
  import { createStorageOperations as external_keyValueStore_index_js_createStorageOperations } from "./keyValueStore/index.js";
6
6
  import { DdbServiceManifestLoader } from "./serviceDiscovery/index.js";
7
- const createApiCoreDdb = ({ documentClient })=>{
7
+ const createApiCoreDdb = ({ documentClient, scopeTenant })=>{
8
8
  ServiceDiscovery.setLoader(new DdbServiceManifestLoader(documentClient));
9
9
  return {
10
10
  usersStorageOperations: createStorageOperations({
11
- documentClient
11
+ documentClient,
12
+ scopeTenant
12
13
  }),
13
14
  tenancyStorageOperations: index_js_createStorageOperations({
14
15
  documentClient
15
16
  }),
16
17
  securityStorageOperations: external_security_index_js_createStorageOperations({
17
- documentClient
18
+ documentClient,
19
+ scopeTenant
18
20
  }),
19
21
  keyValueStorageOperations: external_keyValueStore_index_js_createStorageOperations({
20
22
  documentClient
@@ -1 +1 @@
1
- {"version":3,"file":"createApiCoreDdb.js","sources":["../src/createApiCoreDdb.ts"],"sourcesContent":["import type { ApiCoreStorageOperations } from \"@webiny/api-core/types/core.js\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { ServiceDiscovery } from \"@webiny/api-core/features/serviceDiscovery/index.js\";\nimport { createStorageOperations as createUsersStorageOperations } from \"./adminUsers/index.js\";\nimport { createStorageOperations as createTenancyStorageOperations } from \"./tenancy/index.js\";\nimport { createStorageOperations as createSecurityStorageOperations } from \"./security/index.js\";\nimport { createStorageOperations as createKeyValueStorageOperations } from \"./keyValueStore/index.js\";\nimport { DdbServiceManifestLoader } from \"./serviceDiscovery/index.js\";\n\ninterface CreateApiCoreDdbParams {\n documentClient: DynamoDBDocument;\n}\n\nexport const createApiCoreDdb = ({\n documentClient\n}: CreateApiCoreDdbParams): ApiCoreStorageOperations => {\n ServiceDiscovery.setLoader(new DdbServiceManifestLoader(documentClient));\n\n return {\n usersStorageOperations: createUsersStorageOperations({\n documentClient\n }),\n tenancyStorageOperations: createTenancyStorageOperations({\n documentClient\n }),\n securityStorageOperations: createSecurityStorageOperations({\n documentClient\n }),\n keyValueStorageOperations: createKeyValueStorageOperations({\n documentClient\n })\n };\n};\n"],"names":["createApiCoreDdb","documentClient","ServiceDiscovery","DdbServiceManifestLoader","createUsersStorageOperations","createTenancyStorageOperations","createSecurityStorageOperations","createKeyValueStorageOperations"],"mappings":";;;;;;AAaO,MAAMA,mBAAmB,CAAC,EAC7BC,cAAc,EACO;IACrBC,iBAAiB,SAAS,CAAC,IAAIC,yBAAyBF;IAExD,OAAO;QACH,wBAAwBG,wBAA6B;YACjDH;QACJ;QACA,0BAA0BI,iCAA+B;YACrDJ;QACJ;QACA,2BAA2BK,mDAAgC;YACvDL;QACJ;QACA,2BAA2BM,wDAAgC;YACvDN;QACJ;IACJ;AACJ"}
1
+ {"version":3,"file":"createApiCoreDdb.js","sources":["../src/createApiCoreDdb.ts"],"sourcesContent":["import type { ApiCoreStorageOperations } from \"@webiny/api-core/types/core.js\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { ServiceDiscovery } from \"@webiny/api-core/features/serviceDiscovery/index.js\";\nimport { createStorageOperations as createUsersStorageOperations } from \"./adminUsers/index.js\";\nimport { createStorageOperations as createTenancyStorageOperations } from \"./tenancy/index.js\";\nimport { createStorageOperations as createSecurityStorageOperations } from \"./security/index.js\";\nimport { createStorageOperations as createKeyValueStorageOperations } from \"./keyValueStore/index.js\";\nimport { DdbServiceManifestLoader } from \"./serviceDiscovery/index.js\";\nimport type { ScopeTenant } from \"@webiny/api-core/features/tenancy/ScopeTenant/index.js\";\n\ninterface CreateApiCoreDdbParams {\n documentClient: DynamoDBDocument;\n /**\n * The tenant the storage acts on: its tenant scope's. The tenant records and the key-value store\n * don't use it (the tenant registry is tenant-neutral, and the store is keyed by its own scope).\n */\n scopeTenant: ScopeTenant.Interface;\n}\n\nexport const createApiCoreDdb = ({\n documentClient,\n scopeTenant\n}: CreateApiCoreDdbParams): ApiCoreStorageOperations => {\n ServiceDiscovery.setLoader(new DdbServiceManifestLoader(documentClient));\n\n return {\n usersStorageOperations: createUsersStorageOperations({\n documentClient,\n scopeTenant\n }),\n tenancyStorageOperations: createTenancyStorageOperations({\n documentClient\n }),\n securityStorageOperations: createSecurityStorageOperations({\n documentClient,\n scopeTenant\n }),\n keyValueStorageOperations: createKeyValueStorageOperations({\n documentClient\n })\n };\n};\n"],"names":["createApiCoreDdb","documentClient","scopeTenant","ServiceDiscovery","DdbServiceManifestLoader","createUsersStorageOperations","createTenancyStorageOperations","createSecurityStorageOperations","createKeyValueStorageOperations"],"mappings":";;;;;;AAmBO,MAAMA,mBAAmB,CAAC,EAC7BC,cAAc,EACdC,WAAW,EACU;IACrBC,iBAAiB,SAAS,CAAC,IAAIC,yBAAyBH;IAExD,OAAO;QACH,wBAAwBI,wBAA6B;YACjDJ;YACAC;QACJ;QACA,0BAA0BI,iCAA+B;YACrDL;QACJ;QACA,2BAA2BM,mDAAgC;YACvDN;YACAC;QACJ;QACA,2BAA2BM,wDAAgC;YACvDP;QACJ;IACJ;AACJ"}
@@ -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":";AAQO,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;IAEA,YAAY;QACR,OAAO,IAAI,CAAC,MAAM;IACtB;AACJ"}
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<void>;
15
- delete(key: string, scope: string): Promise<void>;
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
- const ttl = Number(entry.expiresAt);
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
- await this.entity.put({
87
+ const item = {
43
88
  ...keys,
44
89
  TYPE: "KeyValueStore",
45
- expiresAt: options?.expiresAt ? Math.floor(options.expiresAt.getTime() / 1000) : void 0,
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
- await this.entity.delete(this.table.createKeys({
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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;IACJ;IAOQ,eAAeH,MAA0D,EAAE;QAC/E,MAAM,EAAEb,GAAG,EAAEC,KAAK,EAAE,GAAGY;QACvB,MAAMX,YAAY,IAAI,CAAC,eAAe,CAACF,KAAKC;QAC5C,MAAMuB,YAAY,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC;YAAEtB;QAAU;QACpD,MAAMS,WAAW,IAAI,CAAC,KAAK,CAAC,cAAc,CAACE;QAE3C,OAAO;YAAE,GAAGW,SAAS;YAAE,GAAGb,QAAQ;QAAC;IACvC;AACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webiny/api-core-ddb",
3
- "version": "0.0.0-unstable.0d717d18dd",
3
+ "version": "0.0.0-unstable.292eb6dc15",
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": "0.0.0-unstable.0d717d18dd",
25
- "@webiny/api-core": "0.0.0-unstable.0d717d18dd",
26
- "@webiny/aws-sdk": "0.0.0-unstable.0d717d18dd",
27
- "@webiny/db-dynamodb": "0.0.0-unstable.0d717d18dd",
28
- "@webiny/error": "0.0.0-unstable.0d717d18dd",
29
- "@webiny/feature": "0.0.0-unstable.0d717d18dd"
24
+ "@webiny/api": "0.0.0-unstable.292eb6dc15",
25
+ "@webiny/api-core": "0.0.0-unstable.292eb6dc15",
26
+ "@webiny/aws-sdk": "0.0.0-unstable.292eb6dc15",
27
+ "@webiny/db-dynamodb": "0.0.0-unstable.292eb6dc15",
28
+ "@webiny/error": "0.0.0-unstable.292eb6dc15",
29
+ "@webiny/feature": "0.0.0-unstable.292eb6dc15"
30
30
  },
31
31
  "devDependencies": {
32
- "@webiny/api": "0.0.0-unstable.0d717d18dd",
33
- "@webiny/build-tools": "0.0.0-unstable.0d717d18dd",
34
- "@webiny/project-utils": "0.0.0-unstable.0d717d18dd",
32
+ "@webiny/api": "0.0.0-unstable.292eb6dc15",
33
+ "@webiny/build-tools": "0.0.0-unstable.292eb6dc15",
35
34
  "jest-dynalite": "3.6.1",
36
- "rimraf": "6.1.3",
37
- "typescript": "7.0.2"
35
+ "rimraf": "6.1.4",
36
+ "typescript": "7.0.2",
37
+ "vitest": "5.1.1"
38
38
  },
39
39
  "publishConfig": {
40
40
  "access": "public"
package/security/index.js CHANGED
@@ -2,7 +2,11 @@ import error from "@webiny/error";
2
2
  import { createApiKeyEntity, createRoleEntity, createTeamEntity } from "./definitions/entities.js";
3
3
  import { createTable, sortItems } from "@webiny/db-dynamodb";
4
4
  const createStorageOperations = (params)=>{
5
- const { table: tableName, documentClient } = params;
5
+ const { table: tableName, documentClient, scopeTenant } = params;
6
+ const inScope = (record)=>({
7
+ ...record,
8
+ tenant: scopeTenant.getId()
9
+ });
6
10
  const table = createTable({
7
11
  name: tableName || process.env.DB_TABLE,
8
12
  documentClient
@@ -45,7 +49,8 @@ const createStorageOperations = (params)=>{
45
49
  TYPE: "security.team"
46
50
  });
47
51
  return {
48
- async createApiKey ({ apiKey }) {
52
+ async createApiKey (params) {
53
+ const apiKey = inScope(params.apiKey);
49
54
  const keys = {
50
55
  ...createApiKeyKeys(apiKey),
51
56
  ...createApiKeyGsiKeys(apiKey)
@@ -65,7 +70,8 @@ const createStorageOperations = (params)=>{
65
70
  });
66
71
  }
67
72
  },
68
- async createRole ({ role }) {
73
+ async createRole (params) {
74
+ const role = inScope(params.role);
69
75
  const keys = {
70
76
  ...createRoleKeys(role),
71
77
  ...createRoleGsiKeys(role)
@@ -85,7 +91,8 @@ const createStorageOperations = (params)=>{
85
91
  });
86
92
  }
87
93
  },
88
- async createTeam ({ team }) {
94
+ async createTeam (params) {
95
+ const team = inScope(params.team);
89
96
  const keys = {
90
97
  ...createTeamKeys(team),
91
98
  ...createTeamGsiKeys(team)
@@ -105,8 +112,8 @@ const createStorageOperations = (params)=>{
105
112
  });
106
113
  }
107
114
  },
108
- async deleteApiKey ({ apiKey }) {
109
- const keys = createApiKeyKeys(apiKey);
115
+ async deleteApiKey (params) {
116
+ const keys = createApiKeyKeys(inScope(params.apiKey));
110
117
  try {
111
118
  await entities.apiKeys.delete(keys);
112
119
  } catch (err) {
@@ -119,7 +126,8 @@ const createStorageOperations = (params)=>{
119
126
  });
120
127
  }
121
128
  },
122
- async deleteRole ({ role }) {
129
+ async deleteRole (params) {
130
+ const role = inScope(params.role);
123
131
  const keys = createRoleKeys(role);
124
132
  try {
125
133
  await entities.roles.delete(keys);
@@ -134,7 +142,8 @@ const createStorageOperations = (params)=>{
134
142
  });
135
143
  }
136
144
  },
137
- async deleteTeam ({ team }) {
145
+ async deleteTeam (params) {
146
+ const team = inScope(params.team);
138
147
  const keys = createTeamKeys(team);
139
148
  try {
140
149
  await entities.teams.delete(keys);
@@ -149,7 +158,9 @@ const createStorageOperations = (params)=>{
149
158
  });
150
159
  }
151
160
  },
152
- async getApiKey ({ id, tenant }) {
161
+ async getApiKey (params) {
162
+ const { id } = params;
163
+ const tenant = scopeTenant.getId();
153
164
  const keys = createApiKeyKeys({
154
165
  id,
155
166
  tenant
@@ -168,7 +179,9 @@ const createStorageOperations = (params)=>{
168
179
  });
169
180
  }
170
181
  },
171
- async getApiKeyByToken ({ tenant, token }) {
182
+ async getApiKeyByToken (params) {
183
+ const { token } = params;
184
+ const tenant = scopeTenant.getId();
172
185
  const queryParams = {
173
186
  partitionKey: `T#${tenant}#API_KEYS`,
174
187
  options: {
@@ -190,7 +203,9 @@ const createStorageOperations = (params)=>{
190
203
  });
191
204
  }
192
205
  },
193
- async getApiKeyBySlug ({ tenant, slug }) {
206
+ async getApiKeyBySlug (params) {
207
+ const { slug } = params;
208
+ const tenant = scopeTenant.getId();
194
209
  const queryParams = {
195
210
  partitionKey: `T#${tenant}#API_KEYS`,
196
211
  options: {
@@ -212,7 +227,9 @@ const createStorageOperations = (params)=>{
212
227
  });
213
228
  }
214
229
  },
215
- async getRole ({ where: { tenant, id, slug } }) {
230
+ async getRole ({ where }) {
231
+ const { id, slug } = where;
232
+ const tenant = scopeTenant.getId();
216
233
  try {
217
234
  if (id) {
218
235
  const result = await entities.roles.get(createRoleKeys({
@@ -240,7 +257,9 @@ const createStorageOperations = (params)=>{
240
257
  });
241
258
  }
242
259
  },
243
- async getTeam ({ where: { tenant, id, slug } }) {
260
+ async getTeam ({ where }) {
261
+ const { id, slug } = where;
262
+ const tenant = scopeTenant.getId();
244
263
  try {
245
264
  if (id) {
246
265
  const result = await entities.teams.get(createTeamKeys({
@@ -268,7 +287,8 @@ const createStorageOperations = (params)=>{
268
287
  });
269
288
  }
270
289
  },
271
- async listApiKeys ({ where: { tenant }, sort }) {
290
+ async listApiKeys ({ sort }) {
291
+ const tenant = scopeTenant.getId();
272
292
  let items;
273
293
  try {
274
294
  items = await entities.apiKeys.queryAll({
@@ -288,7 +308,9 @@ const createStorageOperations = (params)=>{
288
308
  sort
289
309
  }).map((item)=>item.data);
290
310
  },
291
- async listRoles ({ where: { tenant, id_in, slug_in }, sort }) {
311
+ async listRoles ({ where, sort }) {
312
+ const { id_in, slug_in } = where;
313
+ const tenant = scopeTenant.getId();
292
314
  let items;
293
315
  try {
294
316
  const ddbItems = await entities.roles.queryAll({
@@ -312,7 +334,9 @@ const createStorageOperations = (params)=>{
312
334
  if (Array.isArray(slug_in)) return items.filter((item)=>slug_in.includes(item.slug));
313
335
  return items;
314
336
  },
315
- async listTeams ({ where: { tenant, id_in, slug_in }, sort }) {
337
+ async listTeams ({ where, sort }) {
338
+ const { id_in, slug_in } = where;
339
+ const tenant = scopeTenant.getId();
316
340
  let items;
317
341
  try {
318
342
  const ddbRecords = await entities.teams.queryAll({
@@ -336,7 +360,8 @@ const createStorageOperations = (params)=>{
336
360
  if (Array.isArray(slug_in)) return items.filter((item)=>slug_in.includes(item.slug));
337
361
  return items;
338
362
  },
339
- async updateApiKey ({ apiKey }) {
363
+ async updateApiKey (params) {
364
+ const apiKey = inScope(params.apiKey);
340
365
  const keys = {
341
366
  ...createApiKeyKeys(apiKey),
342
367
  ...createApiKeyGsiKeys(apiKey)
@@ -356,7 +381,8 @@ const createStorageOperations = (params)=>{
356
381
  });
357
382
  }
358
383
  },
359
- async updateRole ({ role }) {
384
+ async updateRole (params) {
385
+ const role = inScope(params.role);
360
386
  const keys = createRoleKeys(role);
361
387
  try {
362
388
  await entities.roles.put({
@@ -375,7 +401,8 @@ const createStorageOperations = (params)=>{
375
401
  });
376
402
  }
377
403
  },
378
- async updateTeam ({ team }) {
404
+ async updateTeam (params) {
405
+ const team = inScope(params.team);
379
406
  const keys = createTeamKeys(team);
380
407
  try {
381
408
  await entities.teams.put({
@@ -1 +1 @@
1
- {"version":3,"file":"security/index.js","sources":["../../src/security/index.ts"],"sourcesContent":["import type { SecurityStorageParams } from \"./types.js\";\nimport type {\n StorageApiKey,\n StorageRole,\n SecurityStorageOperations,\n StorageTeam\n} from \"@webiny/api-core/types/security.js\";\nimport WebinyError from \"@webiny/error\";\nimport { createApiKeyEntity, createRoleEntity, createTeamEntity } from \"./definitions/entities.js\";\nimport { createTable, type IEntityQueryOneParams, sortItems } from \"@webiny/db-dynamodb\";\n\nexport const createStorageOperations = (\n params: SecurityStorageParams\n): SecurityStorageOperations => {\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 apiKeys: createApiKeyEntity(table.table),\n roles: createRoleEntity(table.table),\n teams: createTeamEntity(table.table)\n };\n\n const createApiKeyKeys = ({ id, tenant }: Pick<StorageApiKey, \"id\" | \"tenant\">) => ({\n PK: `T#${tenant}#API_KEY#${id}`,\n SK: `A`,\n GSI_TENANT: tenant,\n TYPE: \"security.apiKey\"\n });\n\n const createApiKeyGsiKeys = ({\n slug,\n token,\n tenant\n }: Pick<StorageApiKey, \"slug\" | \"tenant\" | \"token\">) => ({\n GSI1_PK: `T#${tenant}#API_KEYS`,\n GSI1_SK: token,\n GSI2_PK: `T#${tenant}#API_KEYS`,\n GSI2_SK: slug\n });\n\n const createRoleKeys = (role: Pick<StorageRole, \"tenant\" | \"id\">) => ({\n PK: `T#${role.tenant}#ROLE#${role.id}`,\n SK: `A`\n });\n\n const createRoleGsiKeys = (role: Pick<StorageRole, \"tenant\" | \"slug\">) => ({\n GSI1_PK: `T#${role.tenant}#ROLES`,\n GSI1_SK: role.slug,\n GSI_TENANT: role.tenant as string,\n TYPE: \"security.role\"\n });\n\n const createTeamKeys = (team: Pick<StorageTeam, \"tenant\" | \"id\">) => ({\n PK: `T#${team.tenant}#TEAM#${team.id}`,\n SK: `A`\n });\n\n const createTeamGsiKeys = (team: Pick<StorageTeam, \"tenant\" | \"slug\">) => ({\n GSI1_PK: `T#${team.tenant}#TEAMS`,\n GSI1_SK: team.slug,\n GSI_TENANT: team.tenant as string,\n TYPE: \"security.team\"\n });\n\n return {\n async createApiKey({ apiKey }): Promise<void> {\n const keys = {\n ...createApiKeyKeys(apiKey),\n ...createApiKeyGsiKeys(apiKey)\n };\n\n try {\n await entities.apiKeys.put({\n data: apiKey,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create api key.\",\n code: \"CREATE_API_KEY_ERROR\",\n data: { keys }\n });\n }\n },\n async createRole({ role }): Promise<void> {\n const keys = {\n ...createRoleKeys(role),\n ...createRoleGsiKeys(role)\n };\n\n try {\n await entities.roles.put({\n data: role,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create role.\",\n code: \"CREATE_ROLE_ERROR\",\n data: { keys }\n });\n }\n },\n async createTeam({ team }): Promise<void> {\n const keys = {\n ...createTeamKeys(team),\n ...createTeamGsiKeys(team)\n };\n\n try {\n await entities.teams.put({\n data: team,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create team.\",\n code: \"CREATE_TEAM_ERROR\",\n data: { keys }\n });\n }\n },\n async deleteApiKey({ apiKey }) {\n const keys = createApiKeyKeys(apiKey);\n\n try {\n await entities.apiKeys.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update api key.\",\n code: \"UPDATE_API_KEY_ERROR\",\n data: { keys }\n });\n }\n },\n async deleteRole({ role }) {\n const keys = createRoleKeys(role);\n\n try {\n await entities.roles.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete role.\",\n code: \"CREATE_DELETE_ERROR\",\n data: { keys, role }\n });\n }\n },\n async deleteTeam({ team }) {\n const keys = createTeamKeys(team);\n\n try {\n await entities.teams.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete team.\",\n code: \"CREATE_DELETE_ERROR\",\n data: { keys, team }\n });\n }\n },\n async getApiKey({ id, tenant }) {\n const keys = createApiKeyKeys({ id, tenant });\n\n try {\n const response = await entities.apiKeys.get(keys);\n\n return response?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key.\",\n code: \"GET_API_KEY_ERROR\",\n data: { id, keys }\n });\n }\n },\n async getApiKeyByToken({ tenant, token }) {\n const queryParams: IEntityQueryOneParams = {\n partitionKey: `T#${tenant}#API_KEYS`,\n options: {\n eq: token,\n index: \"GSI1\"\n }\n };\n\n try {\n const result = await entities.apiKeys.queryOne(queryParams);\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key by token.\",\n code: \"GET_BY_TOKEN_API_KEY_ERROR\",\n data: { partitionKey: queryParams.partitionKey, options: queryParams.options }\n });\n }\n },\n async getApiKeyBySlug({ tenant, slug }) {\n const queryParams: IEntityQueryOneParams = {\n partitionKey: `T#${tenant}#API_KEYS`,\n options: {\n eq: slug,\n index: \"GSI2\"\n }\n };\n\n try {\n const result = await entities.apiKeys.queryOne(queryParams);\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key by slug.\",\n code: \"GET_BY_SLUG_API_KEY_ERROR\",\n data: { partitionKey: queryParams.partitionKey, options: queryParams.options }\n });\n }\n },\n async getRole({ where: { tenant, id, slug } }) {\n try {\n if (id) {\n const result = await entities.roles.get(createRoleKeys({ tenant, id }));\n return result?.data || null;\n }\n const result = await entities.roles.queryOne({\n partitionKey: `T#${tenant}#ROLES`,\n options: {\n index: \"GSI1\",\n eq: slug\n }\n });\n\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load role.\",\n code: \"GET_ROLE_ERROR\",\n data: { id, slug }\n });\n }\n },\n async getTeam({ where: { tenant, id, slug } }) {\n try {\n if (id) {\n const result = await entities.teams.get(createTeamKeys({ tenant, id }));\n\n return result?.data || null;\n }\n\n const result = await entities.teams.queryOne({\n partitionKey: `T#${tenant}#TEAMS`,\n options: {\n index: \"GSI1\",\n eq: slug\n }\n });\n\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load team.\",\n code: \"GET_TEAM_ERROR\",\n data: { id, slug }\n });\n }\n },\n async listApiKeys({ where: { tenant }, sort }): Promise<StorageApiKey[]> {\n let items;\n try {\n items = await entities.apiKeys.queryAll({\n partitionKey: `T#${tenant}#API_KEYS`,\n options: {\n index: \"GSI1\"\n }\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list api keys.\",\n code: \"LIST_API_KEY_ERROR\"\n });\n }\n\n return sortItems({ items, sort }).map(item => item.data);\n },\n async listRoles({ where: { tenant, id_in, slug_in }, sort }): Promise<StorageRole[]> {\n let items: StorageRole[];\n try {\n const ddbItems = await entities.roles.queryAll({\n partitionKey: `T#${tenant}#ROLES`,\n options: {\n index: \"GSI1\"\n }\n });\n items = ddbItems.map(item => item.data);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list roles.\",\n code: \"LIST_ROLE_ERROR\"\n });\n }\n\n items = sortItems({ items, sort });\n\n if (Array.isArray(id_in)) {\n return items.filter(item => id_in.includes(item.id));\n }\n\n if (Array.isArray(slug_in)) {\n return items.filter(item => slug_in.includes(item.slug));\n }\n\n return items;\n },\n async listTeams({ where: { tenant, id_in, slug_in }, sort }): Promise<StorageTeam[]> {\n let items: StorageTeam[];\n try {\n const ddbRecords = await entities.teams.queryAll({\n partitionKey: `T#${tenant}#TEAMS`,\n options: {\n index: \"GSI1\"\n }\n });\n\n items = ddbRecords.map(item => item.data);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list teams.\",\n code: \"LIST_TEAM_ERROR\"\n });\n }\n\n items = sortItems({ items, sort });\n\n if (Array.isArray(id_in)) {\n return items.filter(item => id_in.includes(item.id));\n }\n\n if (Array.isArray(slug_in)) {\n return items.filter(item => slug_in.includes(item.slug));\n }\n return items;\n },\n async updateApiKey({ apiKey }): Promise<void> {\n const keys = {\n ...createApiKeyKeys(apiKey),\n ...createApiKeyGsiKeys(apiKey)\n };\n\n try {\n await entities.apiKeys.put({\n data: apiKey,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update api key.\",\n code: \"UPDATE_API_KEY_ERROR\",\n data: { keys }\n });\n }\n },\n async updateRole({ role }): Promise<void> {\n const keys = createRoleKeys(role);\n\n try {\n await entities.roles.put({\n data: role,\n ...keys,\n ...createRoleGsiKeys(role)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update role.\",\n code: \"UPDATE_ROLE_ERROR\",\n data: { keys, role }\n });\n }\n },\n async updateTeam({ team }): Promise<void> {\n const keys = createTeamKeys(team);\n\n try {\n await entities.teams.put({\n data: team,\n ...keys,\n ...createTeamGsiKeys(team)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update team.\",\n code: \"UPDATE_TEAM_ERROR\",\n data: { keys, team }\n });\n }\n }\n };\n};\n"],"names":["createStorageOperations","params","tableName","documentClient","table","createTable","process","entities","createApiKeyEntity","createRoleEntity","createTeamEntity","createApiKeyKeys","id","tenant","createApiKeyGsiKeys","slug","token","createRoleKeys","role","createRoleGsiKeys","createTeamKeys","team","createTeamGsiKeys","apiKey","keys","err","WebinyError","response","queryParams","result","sort","items","sortItems","item","id_in","slug_in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AAQ,QAAQ,CAACF,KAAK,IAAI;YAE1D,OAAOF;QACX;QACA,MAAM,cAAa,EAAER,MAAM,EAAE;YACzB,MAAMC,OAAO;gBACT,GAAGb,iBAAiBY,OAAO;gBAC3B,GAAGT,oBAAoBS,OAAO;YAClC;YAEA,IAAI;gBACA,MAAMhB,SAAS,OAAO,CAAC,GAAG,CAAC;oBACvB,MAAMgB;oBACN,GAAGC,IAAI;gBACX;YACJ,EAAE,OAAOC,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;oBAAK;gBACjB;YACJ;QACJ;QACA,MAAM,YAAW,EAAEN,IAAI,EAAE;YACrB,MAAMM,OAAOP,eAAeC;YAE5B,IAAI;gBACA,MAAMX,SAAS,KAAK,CAAC,GAAG,CAAC;oBACrB,MAAMW;oBACN,GAAGM,IAAI;oBACP,GAAGL,kBAAkBD,KAAK;gBAC9B;YACJ,EAAE,OAAOO,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;wBAAMN;oBAAK;gBACvB;YACJ;QACJ;QACA,MAAM,YAAW,EAAEG,IAAI,EAAE;YACrB,MAAMG,OAAOJ,eAAeC;YAE5B,IAAI;gBACA,MAAMd,SAAS,KAAK,CAAC,GAAG,CAAC;oBACrB,MAAMc;oBACN,GAAGG,IAAI;oBACP,GAAGF,kBAAkBD,KAAK;gBAC9B;YACJ,EAAE,OAAOI,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;wBAAMH;oBAAK;gBACvB;YACJ;QACJ;IACJ;AACJ"}
1
+ {"version":3,"file":"security/index.js","sources":["../../src/security/index.ts"],"sourcesContent":["import type { SecurityStorageParams } from \"./types.js\";\nimport type {\n StorageApiKey,\n StorageRole,\n SecurityStorageOperations,\n StorageTeam\n} from \"@webiny/api-core/types/security.js\";\nimport WebinyError from \"@webiny/error\";\nimport { createApiKeyEntity, createRoleEntity, createTeamEntity } from \"./definitions/entities.js\";\nimport { createTable, type IEntityQueryOneParams, sortItems } from \"@webiny/db-dynamodb\";\n\nexport const createStorageOperations = (\n params: SecurityStorageParams\n): SecurityStorageOperations => {\n const { table: tableName, documentClient, scopeTenant } = params;\n\n /** The record with its scope's tenant, whatever tenant it carries. */\n const inScope = <T extends { tenant?: string | null }>(record: T): T & { tenant: string } => {\n return { ...record, tenant: scopeTenant.getId() };\n };\n\n const table = createTable({\n name: tableName || (process.env.DB_TABLE as string),\n documentClient\n });\n\n const entities = {\n apiKeys: createApiKeyEntity(table.table),\n roles: createRoleEntity(table.table),\n teams: createTeamEntity(table.table)\n };\n\n const createApiKeyKeys = ({ id, tenant }: Pick<StorageApiKey, \"id\" | \"tenant\">) => ({\n PK: `T#${tenant}#API_KEY#${id}`,\n SK: `A`,\n GSI_TENANT: tenant,\n TYPE: \"security.apiKey\"\n });\n\n const createApiKeyGsiKeys = ({\n slug,\n token,\n tenant\n }: Pick<StorageApiKey, \"slug\" | \"tenant\" | \"token\">) => ({\n GSI1_PK: `T#${tenant}#API_KEYS`,\n GSI1_SK: token,\n GSI2_PK: `T#${tenant}#API_KEYS`,\n GSI2_SK: slug\n });\n\n const createRoleKeys = (role: Pick<StorageRole, \"tenant\" | \"id\">) => ({\n PK: `T#${role.tenant}#ROLE#${role.id}`,\n SK: `A`\n });\n\n const createRoleGsiKeys = (role: Pick<StorageRole, \"tenant\" | \"slug\">) => ({\n GSI1_PK: `T#${role.tenant}#ROLES`,\n GSI1_SK: role.slug,\n GSI_TENANT: role.tenant as string,\n TYPE: \"security.role\"\n });\n\n const createTeamKeys = (team: Pick<StorageTeam, \"tenant\" | \"id\">) => ({\n PK: `T#${team.tenant}#TEAM#${team.id}`,\n SK: `A`\n });\n\n const createTeamGsiKeys = (team: Pick<StorageTeam, \"tenant\" | \"slug\">) => ({\n GSI1_PK: `T#${team.tenant}#TEAMS`,\n GSI1_SK: team.slug,\n GSI_TENANT: team.tenant as string,\n TYPE: \"security.team\"\n });\n\n return {\n async createApiKey(params): Promise<void> {\n const apiKey = inScope(params.apiKey);\n const keys = {\n ...createApiKeyKeys(apiKey),\n ...createApiKeyGsiKeys(apiKey)\n };\n\n try {\n await entities.apiKeys.put({\n data: apiKey,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create api key.\",\n code: \"CREATE_API_KEY_ERROR\",\n data: { keys }\n });\n }\n },\n async createRole(params): Promise<void> {\n const role = inScope(params.role);\n const keys = {\n ...createRoleKeys(role),\n ...createRoleGsiKeys(role)\n };\n\n try {\n await entities.roles.put({\n data: role,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create role.\",\n code: \"CREATE_ROLE_ERROR\",\n data: { keys }\n });\n }\n },\n async createTeam(params): Promise<void> {\n const team = inScope(params.team);\n const keys = {\n ...createTeamKeys(team),\n ...createTeamGsiKeys(team)\n };\n\n try {\n await entities.teams.put({\n data: team,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create team.\",\n code: \"CREATE_TEAM_ERROR\",\n data: { keys }\n });\n }\n },\n async deleteApiKey(params) {\n const keys = createApiKeyKeys(inScope(params.apiKey));\n\n try {\n await entities.apiKeys.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update api key.\",\n code: \"UPDATE_API_KEY_ERROR\",\n data: { keys }\n });\n }\n },\n async deleteRole(params) {\n const role = inScope(params.role);\n const keys = createRoleKeys(role);\n\n try {\n await entities.roles.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete role.\",\n code: \"CREATE_DELETE_ERROR\",\n data: { keys, role }\n });\n }\n },\n async deleteTeam(params) {\n const team = inScope(params.team);\n const keys = createTeamKeys(team);\n\n try {\n await entities.teams.delete(keys);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete team.\",\n code: \"CREATE_DELETE_ERROR\",\n data: { keys, team }\n });\n }\n },\n async getApiKey(params) {\n const { id } = params;\n const tenant = scopeTenant.getId();\n const keys = createApiKeyKeys({ id, tenant });\n\n try {\n const response = await entities.apiKeys.get(keys);\n\n return response?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key.\",\n code: \"GET_API_KEY_ERROR\",\n data: { id, keys }\n });\n }\n },\n async getApiKeyByToken(params) {\n const { token } = params;\n const tenant = scopeTenant.getId();\n const queryParams: IEntityQueryOneParams = {\n partitionKey: `T#${tenant}#API_KEYS`,\n options: {\n eq: token,\n index: \"GSI1\"\n }\n };\n\n try {\n const result = await entities.apiKeys.queryOne(queryParams);\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key by token.\",\n code: \"GET_BY_TOKEN_API_KEY_ERROR\",\n data: { partitionKey: queryParams.partitionKey, options: queryParams.options }\n });\n }\n },\n async getApiKeyBySlug(params) {\n const { slug } = params;\n const tenant = scopeTenant.getId();\n const queryParams: IEntityQueryOneParams = {\n partitionKey: `T#${tenant}#API_KEYS`,\n options: {\n eq: slug,\n index: \"GSI2\"\n }\n };\n\n try {\n const result = await entities.apiKeys.queryOne(queryParams);\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key by slug.\",\n code: \"GET_BY_SLUG_API_KEY_ERROR\",\n data: { partitionKey: queryParams.partitionKey, options: queryParams.options }\n });\n }\n },\n async getRole({ where }) {\n const { id, slug } = where;\n const tenant = scopeTenant.getId();\n try {\n if (id) {\n const result = await entities.roles.get(createRoleKeys({ tenant, id }));\n return result?.data || null;\n }\n const result = await entities.roles.queryOne({\n partitionKey: `T#${tenant}#ROLES`,\n options: {\n index: \"GSI1\",\n eq: slug\n }\n });\n\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load role.\",\n code: \"GET_ROLE_ERROR\",\n data: { id, slug }\n });\n }\n },\n async getTeam({ where }) {\n const { id, slug } = where;\n const tenant = scopeTenant.getId();\n try {\n if (id) {\n const result = await entities.teams.get(createTeamKeys({ tenant, id }));\n\n return result?.data || null;\n }\n\n const result = await entities.teams.queryOne({\n partitionKey: `T#${tenant}#TEAMS`,\n options: {\n index: \"GSI1\",\n eq: slug\n }\n });\n\n return result?.data || null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load team.\",\n code: \"GET_TEAM_ERROR\",\n data: { id, slug }\n });\n }\n },\n async listApiKeys({ sort }): Promise<StorageApiKey[]> {\n const tenant = scopeTenant.getId();\n let items;\n try {\n items = await entities.apiKeys.queryAll({\n partitionKey: `T#${tenant}#API_KEYS`,\n options: {\n index: \"GSI1\"\n }\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list api keys.\",\n code: \"LIST_API_KEY_ERROR\"\n });\n }\n\n return sortItems({ items, sort }).map(item => item.data);\n },\n async listRoles({ where, sort }): Promise<StorageRole[]> {\n const { id_in, slug_in } = where;\n const tenant = scopeTenant.getId();\n let items: StorageRole[];\n try {\n const ddbItems = await entities.roles.queryAll({\n partitionKey: `T#${tenant}#ROLES`,\n options: {\n index: \"GSI1\"\n }\n });\n items = ddbItems.map(item => item.data);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list roles.\",\n code: \"LIST_ROLE_ERROR\"\n });\n }\n\n items = sortItems({ items, sort });\n\n if (Array.isArray(id_in)) {\n return items.filter(item => id_in.includes(item.id));\n }\n\n if (Array.isArray(slug_in)) {\n return items.filter(item => slug_in.includes(item.slug));\n }\n\n return items;\n },\n async listTeams({ where, sort }): Promise<StorageTeam[]> {\n const { id_in, slug_in } = where;\n const tenant = scopeTenant.getId();\n let items: StorageTeam[];\n try {\n const ddbRecords = await entities.teams.queryAll({\n partitionKey: `T#${tenant}#TEAMS`,\n options: {\n index: \"GSI1\"\n }\n });\n\n items = ddbRecords.map(item => item.data);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list teams.\",\n code: \"LIST_TEAM_ERROR\"\n });\n }\n\n items = sortItems({ items, sort });\n\n if (Array.isArray(id_in)) {\n return items.filter(item => id_in.includes(item.id));\n }\n\n if (Array.isArray(slug_in)) {\n return items.filter(item => slug_in.includes(item.slug));\n }\n return items;\n },\n async updateApiKey(params): Promise<void> {\n const apiKey = inScope(params.apiKey);\n const keys = {\n ...createApiKeyKeys(apiKey),\n ...createApiKeyGsiKeys(apiKey)\n };\n\n try {\n await entities.apiKeys.put({\n data: apiKey,\n ...keys\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update api key.\",\n code: \"UPDATE_API_KEY_ERROR\",\n data: { keys }\n });\n }\n },\n async updateRole(params): Promise<void> {\n const role = inScope(params.role);\n const keys = createRoleKeys(role);\n\n try {\n await entities.roles.put({\n data: role,\n ...keys,\n ...createRoleGsiKeys(role)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update role.\",\n code: \"UPDATE_ROLE_ERROR\",\n data: { keys, role }\n });\n }\n },\n async updateTeam(params): Promise<void> {\n const team = inScope(params.team);\n const keys = createTeamKeys(team);\n\n try {\n await entities.teams.put({\n data: team,\n ...keys,\n ...createTeamGsiKeys(team)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update team.\",\n code: \"UPDATE_TEAM_ERROR\",\n data: { keys, team }\n });\n }\n }\n };\n};\n"],"names":["createStorageOperations","params","tableName","documentClient","scopeTenant","inScope","record","table","createTable","process","entities","createApiKeyEntity","createRoleEntity","createTeamEntity","createApiKeyKeys","id","tenant","createApiKeyGsiKeys","slug","token","createRoleKeys","role","createRoleGsiKeys","createTeamKeys","team","createTeamGsiKeys","apiKey","keys","err","WebinyError","response","queryParams","result","where","sort","items","sortItems","item","id_in","slug_in","ddbItems","Array","ddbRecords"],"mappings":";;;AAWO,MAAMA,0BAA0B,CACnCC;IAEA,MAAM,EAAE,OAAOC,SAAS,EAAEC,cAAc,EAAEC,WAAW,EAAE,GAAGH;IAG1D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ED;wBAAMN;oBAAK;gBACvB;YACJ;QACJ;QACA,MAAM,YAAWpB,MAAM;YACnB,MAAMuB,OAAOnB,QAAQJ,OAAO,IAAI;YAChC,MAAM0B,OAAOJ,eAAeC;YAE5B,IAAI;gBACA,MAAMd,SAAS,KAAK,CAAC,GAAG,CAAC;oBACrB,MAAMc;oBACN,GAAGG,IAAI;oBACP,GAAGF,kBAAkBD,KAAK;gBAC9B;YACJ,EAAE,OAAOI,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;wBAAMH;oBAAK;gBACvB;YACJ;QACJ;IACJ;AACJ"}
@@ -1,4 +1,5 @@
1
1
  import type { DynamoDBDocument } from "@webiny/aws-sdk/client-dynamodb/index.js";
2
+ import type { ScopeTenant } from "@webiny/api-core/features/tenancy/ScopeTenant/index.js";
2
3
  export declare enum ENTITIES {
3
4
  API_KEY = "SecurityApiKey",
4
5
  ROLE = "SecurityRole",
@@ -6,5 +7,7 @@ export declare enum ENTITIES {
6
7
  }
7
8
  export interface SecurityStorageParams {
8
9
  documentClient: DynamoDBDocument;
10
+ /** The tenant the storage acts on: its scope's. */
11
+ scopeTenant: ScopeTenant.Interface;
9
12
  table?: string;
10
13
  }
@@ -1 +1 @@
1
- {"version":3,"file":"security/types.js","sources":["../../src/security/types.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\n\nexport enum ENTITIES {\n API_KEY = \"SecurityApiKey\",\n ROLE = \"SecurityRole\",\n TEAM = \"SecurityTeam\"\n}\n\nexport interface SecurityStorageParams {\n documentClient: DynamoDBDocument;\n table?: string;\n}\n"],"names":["ENTITIES"],"mappings":"AAEO,IAAKA,iBAAQA,WAAAA,GAAAA,SAARA,QAAQ;;;;WAARA"}
1
+ {"version":3,"file":"security/types.js","sources":["../../src/security/types.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport type { ScopeTenant } from \"@webiny/api-core/features/tenancy/ScopeTenant/index.js\";\n\nexport enum ENTITIES {\n API_KEY = \"SecurityApiKey\",\n ROLE = \"SecurityRole\",\n TEAM = \"SecurityTeam\"\n}\n\nexport interface SecurityStorageParams {\n documentClient: DynamoDBDocument;\n /** The tenant the storage acts on: its scope's. */\n scopeTenant: ScopeTenant.Interface;\n table?: string;\n}\n"],"names":["ENTITIES"],"mappings":"AAGO,IAAKA,iBAAQA,WAAAA,GAAAA,SAAAA,QAAAA"}
package/tenancy/index.js CHANGED
@@ -2,9 +2,18 @@ import { createTable } from "@webiny/db-dynamodb";
2
2
  import error from "@webiny/error";
3
3
  import { createTenantEntity } from "./definitions/tenantEntity.js";
4
4
  import { ENTITIES } from "./types.js";
5
+ import { TenantPath } from "@webiny/api-core/features/tenancy/shared/TenantPath.js";
6
+ const MAX_SORT_KEY_BYTES = 1024;
7
+ const createGsi1Sk = (tenant)=>{
8
+ const parentPath = TenantPath.fromStored(tenant).parent();
9
+ return `T#${parentPath ? parentPath.toString() : "null"}#${tenant.createdOn}`;
10
+ };
11
+ const childrenKeyPrefix = (path)=>`T#${path.toString()}#`;
12
+ const grandchildrenKeyPrefix = (path)=>`T#${path.descendantsPrefix()}`;
5
13
  const setTenantDefaults = (item)=>{
6
14
  if (!item.tags) item.tags = [];
7
15
  if (!item.description) item.description = "";
16
+ item.path = TenantPath.fromStored(item).toString();
8
17
  return item;
9
18
  };
10
19
  const createStorageOperations = (params)=>{
@@ -37,26 +46,48 @@ const createStorageOperations = (params)=>{
37
46
  return tenants.map((item)=>item.data).map((item)=>setTenantDefaults(item));
38
47
  },
39
48
  async listTenants (params = {}) {
40
- const { parent } = params;
41
- const options = {
42
- index: "GSI1"
49
+ const { parent, descendants } = params;
50
+ const query = async (options)=>{
51
+ const items = await entities.tenants.queryAll({
52
+ partitionKey: "TENANTS",
53
+ options: {
54
+ index: "GSI1",
55
+ ...options
56
+ }
57
+ });
58
+ return items.map((item)=>setTenantDefaults(item.data));
43
59
  };
44
- if (parent) options.beginsWith = `T#${parent}#`;
45
- else options.gt = " ";
46
- const tenants = await entities.tenants.queryAll({
47
- partitionKey: "TENANTS",
48
- options
60
+ if (!parent) return query({
61
+ gt: " "
49
62
  });
50
- return tenants.map((item)=>item.data).map((item)=>setTenantDefaults(item));
63
+ const children = await query({
64
+ beginsWith: childrenKeyPrefix(parent.path)
65
+ });
66
+ if (!descendants) return children;
67
+ const deeper = await query({
68
+ beginsWith: grandchildrenKeyPrefix(parent.path)
69
+ });
70
+ return [
71
+ ...children,
72
+ ...deeper
73
+ ];
51
74
  },
52
75
  async createTenant (data) {
53
76
  const keys = {
54
77
  PK: `T#${data.id}`,
55
78
  SK: "A",
56
79
  GSI1_PK: "TENANTS",
57
- GSI1_SK: `T#${data.parent}#${data.createdOn}`,
80
+ GSI1_SK: createGsi1Sk(data),
58
81
  GSI_TENANT: data.id
59
82
  };
83
+ if (Buffer.byteLength(keys.GSI1_SK, "utf8") > MAX_SORT_KEY_BYTES) throw new error({
84
+ message: `Tenant "${data.id}" is nested too deeply: its path "${data.path}" is too long to be stored.`,
85
+ code: "TENANT_PATH_TOO_LONG",
86
+ data: {
87
+ id: data.id,
88
+ path: data.path
89
+ }
90
+ });
60
91
  try {
61
92
  await entities.tenants.put({
62
93
  TYPE: "tenancy.tenant",
@@ -81,7 +112,7 @@ const createStorageOperations = (params)=>{
81
112
  PK: tenantPK,
82
113
  SK: "A",
83
114
  GSI1_PK: "TENANTS",
84
- GSI1_SK: `T#${data.parent}#${data.createdOn}`,
115
+ GSI1_SK: createGsi1Sk(data),
85
116
  GSI_TENANT: data.id,
86
117
  TYPE: "tenancy.tenant"
87
118
  };
@@ -1 +1 @@
1
- {"version":3,"file":"tenancy/index.js","sources":["../../src/tenancy/index.ts"],"sourcesContent":["import { createTable, type IEntityQueryAllParams } from \"@webiny/db-dynamodb\";\nimport WebinyError from \"@webiny/error\";\nimport { createTenantEntity } from \"./definitions/tenantEntity.js\";\nimport type { CreateTenancyStorageOperations } from \"./types.js\";\nimport { ENTITIES } from \"./types.js\";\nimport type { ListTenantsParams, Tenant } from \"@webiny/api-core/types/tenancy.js\";\n\nconst setTenantDefaults = (item: Tenant) => {\n if (!item.tags) {\n item.tags = [];\n }\n\n if (!item.description) {\n item.description = \"\";\n }\n\n return item;\n};\n\nexport const createStorageOperations: CreateTenancyStorageOperations = params => {\n const { documentClient } = params;\n\n const tableInstance = createTable({\n name: (process.env.DB_TABLE_TENANCY || process.env.DB_TABLE) as string,\n documentClient\n });\n\n const entities = {\n tenants: createTenantEntity({\n entityName: ENTITIES.TENANT,\n table: tableInstance.table\n })\n };\n\n return {\n getTable() {\n return tableInstance;\n },\n getEntities() {\n return entities;\n },\n\n async getTenantsByIds(ids: string[]): Promise<Tenant[]> {\n const batchReader = entities.tenants.createEntityReader({\n read: ids.map(id => {\n return {\n PK: `T#${id}`,\n SK: \"A\"\n };\n })\n });\n const tenants = await batchReader.execute();\n\n return tenants\n .map(item => {\n return item.data;\n })\n .map(item => {\n return setTenantDefaults(item);\n });\n },\n\n async listTenants(params: ListTenantsParams = {}): Promise<Tenant[]> {\n const { parent } = params;\n\n const options: IEntityQueryAllParams[\"options\"] = {\n index: \"GSI1\"\n };\n\n if (parent) {\n options.beginsWith = `T#${parent}#`;\n } else {\n options.gt = \" \";\n }\n\n const tenants = await entities.tenants.queryAll({\n partitionKey: `TENANTS`,\n options\n });\n\n return tenants\n .map(item => {\n return item.data;\n })\n .map(item => {\n return setTenantDefaults(item);\n });\n },\n\n async createTenant(data: Tenant): Promise<Tenant> {\n const keys = {\n PK: `T#${data.id}`,\n SK: \"A\",\n GSI1_PK: \"TENANTS\",\n GSI1_SK: `T#${data.parent}#${data.createdOn}`,\n GSI_TENANT: data.id\n };\n\n try {\n await entities.tenants.put({\n TYPE: \"tenancy.tenant\",\n ...keys,\n data\n });\n\n return data;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create tenant record.\",\n code: \"CREATE_TENANT_ERROR\",\n data: {\n keys,\n data\n }\n });\n }\n },\n\n async updateTenant(data: Tenant): Promise<Tenant> {\n const tenantPK = `T#${data.id}`;\n\n const keys = {\n PK: tenantPK,\n SK: \"A\",\n GSI1_PK: \"TENANTS\",\n GSI1_SK: `T#${data.parent}#${data.createdOn}`,\n GSI_TENANT: data.id,\n TYPE: \"tenancy.tenant\"\n };\n\n try {\n await entities.tenants.put({\n ...keys,\n data\n });\n return data;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update tenant record.\",\n code: \"CREATE_TENANT_ERROR\",\n data: { keys, data }\n });\n }\n },\n\n async deleteTenant(id: string): Promise<void> {\n await entities.tenants.delete({\n PK: `T#${id}`,\n SK: \"A\"\n });\n }\n };\n};\n"],"names":["setTenantDefaults","item","createStorageOperations","params","documentClient","tableInstance","createTable","process","entities","createTenantEntity","ENTITIES","ids","batchReader","id","tenants","parent","options","data","keys","err","WebinyError","tenantPK"],"mappings":";;;;AAOA,MAAMA,oBAAoB,CAACC;IACvB,IAAI,CAACA,KAAK,IAAI,EACVA,KAAK,IAAI,GAAG,EAAE;IAGlB,IAAI,CAACA,KAAK,WAAW,EACjBA,KAAK,WAAW,GAAG;IAGvB,OAAOA;AACX;AAEO,MAAMC,0BAA0DC,CAAAA;IACnE,MAAM,EAAEC,cAAc,EAAE,GAAGD;IAE3B,MAAME,gBAAgBC,YAAY;QAC9B,MAAOC,QAAQ,GAAG,CAAC,gBAAgB,IAAIA,QAAQ,GAAG,CAAC,QAAQ;QAC3DH;IACJ;IAEA,MAAMI,WAAW;QACb,SAASC,mBAAmB;YACxB,YAAYC,SAAS,MAAM;YAC3B,OAAOL,cAAc,KAAK;QAC9B;IACJ;IAEA,OAAO;QACH;YACI,OAAOA;QACX;QACA;YACI,OAAOG;QACX;QAEA,MAAM,iBAAgBG,GAAa;YAC/B,MAAMC,cAAcJ,SAAS,OAAO,CAAC,kBAAkB,CAAC;gBACpD,MAAMG,IAAI,GAAG,CAACE,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IAAIG;gBACJ,IAAI;gBACJ,SAAS;gBACT,SAAS,CAAC,EAAE,EAAEJ,KAAK,MAAM,CAAC,CAAC,EAAEA,KAAK,SAAS,EAAE;gBAC7C,YAAYA,KAAK,EAAE;gBACnB,MAAM;YACV;YAEA,IAAI;gBACA,MAAMT,SAAS,OAAO,CAAC,GAAG,CAAC;oBACvB,GAAGU,IAAI;oBACPD;gBACJ;gBACA,OAAOA;YACX,EAAE,OAAOE,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAED;wBAAMD;oBAAK;gBACvB;YACJ;QACJ;QAEA,MAAM,cAAaJ,EAAU;YACzB,MAAML,SAAS,OAAO,CAAC,MAAM,CAAC;gBAC1B,IAAI,CAAC,EAAE,EAAEK,IAAI;gBACb,IAAI;YACR;QACJ;IACJ;AACJ"}
1
+ {"version":3,"file":"tenancy/index.js","sources":["../../src/tenancy/index.ts"],"sourcesContent":["import { createTable, type IEntityQueryAllParams } from \"@webiny/db-dynamodb\";\nimport WebinyError from \"@webiny/error\";\nimport { createTenantEntity } from \"./definitions/tenantEntity.js\";\nimport type { CreateTenancyStorageOperations } from \"./types.js\";\nimport { ENTITIES } from \"./types.js\";\nimport type { ListTenantsStorageParams, Tenant } from \"@webiny/api-core/types/tenancy.js\";\nimport { TenantPath } from \"@webiny/api-core/features/tenancy/shared/TenantPath.js\";\n\n/* DynamoDB's limit for a sort key, in bytes. */\nconst MAX_SORT_KEY_BYTES = 1024;\n\n/*\n * The catalog's sort key: `T#` + the parent's path + `#` + createdOn. Root's is `T#null#…` and a\n * first-level tenant's `T#root#…`, exactly the keys written before paths existed, so those records\n * need no backfill. A deeper tenant's is `T#root/A#…`. Ids contain neither `/` nor `#`, so the\n * character after a path tells its children (`T#root/A#…`) from the rest of its subtree\n * (`T#root/A/…`): each is one exact `begins_with`, and a sibling `AB` (`T#root/AB…`) is in neither.\n */\nconst createGsi1Sk = (tenant: Tenant) => {\n const parentPath = TenantPath.fromStored(tenant).parent();\n return `T#${parentPath ? parentPath.toString() : \"null\"}#${tenant.createdOn}`;\n};\n\n/* The key prefix of the tenant's direct children. */\nconst childrenKeyPrefix = (path: TenantPath) => `T#${path.toString()}#`;\n\n/* The key prefix of every tenant below the tenant's children (`T#` + its descendants prefix). */\nconst grandchildrenKeyPrefix = (path: TenantPath) => `T#${path.descendantsPrefix()}`;\n\nconst setTenantDefaults = (item: Tenant) => {\n if (!item.tags) {\n item.tags = [];\n }\n\n if (!item.description) {\n item.description = \"\";\n }\n\n item.path = TenantPath.fromStored(item).toString();\n return item;\n};\n\nexport const createStorageOperations: CreateTenancyStorageOperations = params => {\n const { documentClient } = params;\n\n const tableInstance = createTable({\n name: (process.env.DB_TABLE_TENANCY || process.env.DB_TABLE) as string,\n documentClient\n });\n\n const entities = {\n tenants: createTenantEntity({\n entityName: ENTITIES.TENANT,\n table: tableInstance.table\n })\n };\n\n return {\n getTable() {\n return tableInstance;\n },\n getEntities() {\n return entities;\n },\n\n async getTenantsByIds(ids: string[]): Promise<Tenant[]> {\n const batchReader = entities.tenants.createEntityReader({\n read: ids.map(id => {\n return {\n PK: `T#${id}`,\n SK: \"A\"\n };\n })\n });\n const tenants = await batchReader.execute();\n\n return tenants\n .map(item => {\n return item.data;\n })\n .map(item => {\n return setTenantDefaults(item);\n });\n },\n\n async listTenants(params: ListTenantsStorageParams = {}): Promise<Tenant[]> {\n const { parent, descendants } = params;\n\n const query = async (options: IEntityQueryAllParams[\"options\"]) => {\n const items = await entities.tenants.queryAll({\n partitionKey: `TENANTS`,\n options: { index: \"GSI1\", ...options }\n });\n return items.map(item => setTenantDefaults(item.data));\n };\n\n if (!parent) {\n return query({ gt: \" \" });\n }\n\n const children = await query({ beginsWith: childrenKeyPrefix(parent.path) });\n if (!descendants) {\n return children;\n }\n const deeper = await query({ beginsWith: grandchildrenKeyPrefix(parent.path) });\n return [...children, ...deeper];\n },\n\n async createTenant(data: Tenant): Promise<Tenant> {\n const keys = {\n PK: `T#${data.id}`,\n SK: \"A\",\n GSI1_PK: \"TENANTS\",\n GSI1_SK: createGsi1Sk(data),\n GSI_TENANT: data.id\n };\n\n /* The deeper the tenant, the longer its key: refuse one DynamoDB can't index. */\n if (Buffer.byteLength(keys.GSI1_SK, \"utf8\") > MAX_SORT_KEY_BYTES) {\n throw new WebinyError({\n message: `Tenant \"${data.id}\" is nested too deeply: its path \"${data.path}\" is too long to be stored.`,\n code: \"TENANT_PATH_TOO_LONG\",\n data: { id: data.id, path: data.path }\n });\n }\n\n try {\n await entities.tenants.put({\n TYPE: \"tenancy.tenant\",\n ...keys,\n data\n });\n\n return data;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create tenant record.\",\n code: \"CREATE_TENANT_ERROR\",\n data: {\n keys,\n data\n }\n });\n }\n },\n\n async updateTenant(data: Tenant): Promise<Tenant> {\n const tenantPK = `T#${data.id}`;\n\n const keys = {\n PK: tenantPK,\n SK: \"A\",\n GSI1_PK: \"TENANTS\",\n GSI1_SK: createGsi1Sk(data),\n GSI_TENANT: data.id,\n TYPE: \"tenancy.tenant\"\n };\n\n try {\n await entities.tenants.put({\n ...keys,\n data\n });\n return data;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update tenant record.\",\n code: \"CREATE_TENANT_ERROR\",\n data: { keys, data }\n });\n }\n },\n\n async deleteTenant(id: string): Promise<void> {\n await entities.tenants.delete({\n PK: `T#${id}`,\n SK: \"A\"\n });\n }\n };\n};\n"],"names":["MAX_SORT_KEY_BYTES","createGsi1Sk","tenant","parentPath","TenantPath","childrenKeyPrefix","path","grandchildrenKeyPrefix","setTenantDefaults","item","createStorageOperations","params","documentClient","tableInstance","createTable","process","entities","createTenantEntity","ENTITIES","ids","batchReader","id","tenants","parent","descendants","query","options","items","children","deeper","data","keys","Buffer","WebinyError","err","tenantPK"],"mappings":";;;;;AASA,MAAMA,qBAAqB;AAS3B,MAAMC,eAAe,CAACC;IAClB,MAAMC,a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,MAAM;oBACN,MAAM;wBACFH;wBACAD;oBACJ;gBACJ;YACJ;QACJ;QAEA,MAAM,cAAaA,IAAY;YAC3B,MAAMK,WAAW,CAAC,EAAE,EAAEL,KAAK,EAAE,EAAE;YAE/B,MAAMC,OAAO;gBACT,IAAII;gBACJ,IAAI;gBACJ,SAAS;gBACT,SAASlC,aAAa6B;gBACtB,YAAYA,KAAK,EAAE;gBACnB,MAAM;YACV;YAEA,IAAI;gBACA,MAAMd,SAAS,OAAO,CAAC,GAAG,CAAC;oBACvB,GAAGe,IAAI;oBACPD;gBACJ;gBACA,OAAOA;YACX,EAAE,OAAOI,KAAK;gBACV,MAAMD,MAAAA,IAAgB,CAACC,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEH;wBAAMD;oBAAK;gBACvB;YACJ;QACJ;QAEA,MAAM,cAAaT,EAAU;YACzB,MAAML,SAAS,OAAO,CAAC,MAAM,CAAC;gBAC1B,IAAI,CAAC,EAAE,EAAEK,IAAI;gBACb,IAAI;YACR;QACJ;IACJ;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"tenancy/types.js","sources":["../../src/tenancy/types.ts"],"sourcesContent":["import type { TenancyStorageOperations } from \"@webiny/api-core/types/tenancy.js\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\n\nexport enum ENTITIES {\n TENANT = \"TenancyTenant\"\n}\n\nexport interface CreateTenancyStorageOperations {\n (params: { documentClient: DynamoDBDocument }): TenancyStorageOperations;\n}\n"],"names":["ENTITIES"],"mappings":"AAGO,IAAKA,iBAAQA,WAAAA,GAAAA,SAARA,QAAQ;;WAARA"}
1
+ {"version":3,"file":"tenancy/types.js","sources":["../../src/tenancy/types.ts"],"sourcesContent":["import type { TenancyStorageOperations } from \"@webiny/api-core/types/tenancy.js\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\n\nexport enum ENTITIES {\n TENANT = \"TenancyTenant\"\n}\n\nexport interface CreateTenancyStorageOperations {\n (params: { documentClient: DynamoDBDocument }): TenancyStorageOperations;\n}\n"],"names":["ENTITIES"],"mappings":"AAGO,IAAKA,iBAAQA,WAAAA,GAAAA,SAAAA,QAAAA"}