@webiny/api-opensearch-aws 0.0.0-unstable.0156a4c312

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Webiny
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # @webiny/api-opensearch-aws
2
+
3
+ > [!NOTE]
4
+ > This package is part of the [Webiny](https://www.webiny.com) monorepo.
5
+ > It’s **included in every Webiny project by default** and is not meant to be used as a standalone package.
6
+
7
+ 📘 **Documentation:** [https://www.webiny.com/docs](https://www.webiny.com/docs)
8
+
9
+ ---
10
+
11
+ _This README file is automatically generated during the publish process._
@@ -0,0 +1,2 @@
1
+ import { type OpenSearchClientOptions, type Client } from "@webiny/api-opensearch";
2
+ export declare const createAwsOpenSearchClient: (options: OpenSearchClientOptions) => Client;
@@ -0,0 +1,29 @@
1
+ import { AwsSigv4Signer } from "@opensearch-project/opensearch/aws";
2
+ import { createOpenSearchClient } from "@webiny/api-opensearch";
3
+ import error from "@webiny/error";
4
+ const createAwsOpenSearchClient = (options)=>{
5
+ if (options.auth) return createOpenSearchClient(options);
6
+ const region = process.env.AWS_REGION;
7
+ if (!region) throw new error("Missing AWS_REGION environment variable.", "MISSING_AWS_REGION");
8
+ return createOpenSearchClient({
9
+ ...options,
10
+ ...AwsSigv4Signer({
11
+ region,
12
+ service: "es",
13
+ getCredentials: ()=>{
14
+ const accessKeyId = process.env.AWS_ACCESS_KEY_ID;
15
+ const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
16
+ const sessionToken = process.env.AWS_SESSION_TOKEN;
17
+ if (!accessKeyId || !secretAccessKey) throw new error("Missing AWS credentials (AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY).", "MISSING_AWS_CREDENTIALS");
18
+ return Promise.resolve({
19
+ accessKeyId,
20
+ secretAccessKey,
21
+ sessionToken
22
+ });
23
+ }
24
+ })
25
+ });
26
+ };
27
+ export { createAwsOpenSearchClient };
28
+
29
+ //# sourceMappingURL=createAwsOpenSearchClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createAwsOpenSearchClient.js","sources":["../src/createAwsOpenSearchClient.ts"],"sourcesContent":["import { AwsSigv4Signer } from \"@opensearch-project/opensearch/aws\";\nimport {\n createOpenSearchClient,\n type OpenSearchClientOptions,\n type Client\n} from \"@webiny/api-opensearch\";\nimport WebinyError from \"@webiny/error\";\n\nexport const createAwsOpenSearchClient = (options: OpenSearchClientOptions): Client => {\n if (options.auth) {\n return createOpenSearchClient(options);\n }\n\n const region = process.env.AWS_REGION;\n if (!region) {\n throw new WebinyError(\"Missing AWS_REGION environment variable.\", \"MISSING_AWS_REGION\");\n }\n\n return createOpenSearchClient({\n ...options,\n ...AwsSigv4Signer({\n region,\n service: \"es\",\n getCredentials: () => {\n const accessKeyId = process.env.AWS_ACCESS_KEY_ID;\n const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;\n const sessionToken = process.env.AWS_SESSION_TOKEN;\n\n if (!accessKeyId || !secretAccessKey) {\n throw new WebinyError(\n \"Missing AWS credentials (AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY).\",\n \"MISSING_AWS_CREDENTIALS\"\n );\n }\n\n return Promise.resolve({ accessKeyId, secretAccessKey, sessionToken });\n }\n })\n });\n};\n"],"names":["createAwsOpenSearchClient","options","createOpenSearchClient","region","process","WebinyError","AwsSigv4Signer","accessKeyId","secretAccessKey","sessionToken","Promise"],"mappings":";;;AAQO,MAAMA,4BAA4B,CAACC;IACtC,IAAIA,QAAQ,IAAI,EACZ,OAAOC,uBAAuBD;IAGlC,MAAME,SAASC,QAAQ,GAAG,CAAC,UAAU;IACrC,IAAI,CAACD,QACD,MAAM,IAAIE,MAAY,4CAA4C;IAGtE,OAAOH,uBAAuB;QAC1B,GAAGD,OAAO;QACV,GAAGK,eAAe;YACdH;YACA,SAAS;YACT,gBAAgB;gBACZ,MAAMI,cAAcH,QAAQ,GAAG,CAAC,iBAAiB;gBACjD,MAAMI,kBAAkBJ,QAAQ,GAAG,CAAC,qBAAqB;gBACzD,MAAMK,eAAeL,QAAQ,GAAG,CAAC,iBAAiB;gBAElD,IAAI,CAACG,eAAe,CAACC,iBACjB,MAAM,IAAIH,MACN,yEACA;gBAIR,OAAOK,QAAQ,OAAO,CAAC;oBAAEH;oBAAaC;oBAAiBC;gBAAa;YACxE;QACJ,EAAE;IACN;AACJ"}
package/db/entity.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { type ITable } from "@webiny/db-dynamodb";
2
+ import type { IOpenSearchEntity } from "../db/types.js";
3
+ export interface ICreateOpenSearchEntityParams {
4
+ table: ITable;
5
+ entityName: string;
6
+ }
7
+ export declare const createOpenSearchEntity: (params: ICreateOpenSearchEntityParams) => IOpenSearchEntity;
package/db/entity.js ADDED
@@ -0,0 +1,18 @@
1
+ import { createEntity, standardEntityAttributes } from "@webiny/db-dynamodb";
2
+ const createOpenSearchEntity = (params)=>{
3
+ const { table, entityName } = params;
4
+ return createEntity({
5
+ name: entityName,
6
+ table: table.table,
7
+ attributes: {
8
+ ...standardEntityAttributes,
9
+ index: {
10
+ type: "string",
11
+ required: true
12
+ }
13
+ }
14
+ });
15
+ };
16
+ export { createOpenSearchEntity };
17
+
18
+ //# sourceMappingURL=entity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db/entity.js","sources":["../../src/db/entity.ts"],"sourcesContent":["import { createEntity, type ITable, standardEntityAttributes } from \"@webiny/db-dynamodb\";\nimport type { IOpenSearchEntity, IOpenSearchEntityAttributes } from \"~/db/types.js\";\n\nexport interface ICreateOpenSearchEntityParams {\n table: ITable;\n entityName: string;\n}\n\nexport const createOpenSearchEntity = (\n params: ICreateOpenSearchEntityParams\n): IOpenSearchEntity => {\n const { table, entityName } = params;\n return createEntity<IOpenSearchEntityAttributes>({\n name: entityName,\n table: table.table,\n attributes: {\n ...standardEntityAttributes,\n index: {\n type: \"string\",\n required: true\n }\n }\n });\n};\n"],"names":["createOpenSearchEntity","params","table","entityName","createEntity","standardEntityAttributes"],"mappings":";AAQO,MAAMA,yBAAyB,CAClCC;IAEA,MAAM,EAAEC,KAAK,EAAEC,UAAU,EAAE,GAAGF;IAC9B,OAAOG,aAA0C;QAC7C,MAAMD;QACN,OAAOD,MAAM,KAAK;QAClB,YAAY;YACR,GAAGG,wBAAwB;YAC3B,OAAO;gBACH,MAAM;gBACN,UAAU;YACd;QACJ;IACJ;AACJ"}
package/db/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./table.js";
2
+ export * from "./entity.js";
3
+ export * from "./types.js";
package/db/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./table.js";
2
+ export * from "./entity.js";
3
+ export * from "./types.js";
package/db/table.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { DynamoDBDocument } from "@webiny/aws-sdk/client-dynamodb/index.js";
2
+ import { type ITable } from "@webiny/db-dynamodb";
3
+ export interface ICreateOpenSearchTableParams {
4
+ name?: string;
5
+ documentClient: DynamoDBDocument;
6
+ }
7
+ export declare const createOpenSearchTable: ({ name, documentClient }: ICreateOpenSearchTableParams) => ITable;
package/db/table.js ADDED
@@ -0,0 +1,13 @@
1
+ import { createTable } from "@webiny/db-dynamodb";
2
+ const createOpenSearchTable = ({ name, documentClient })=>createTable({
3
+ name: name || process.env.DB_TABLE_OPENSEARCH,
4
+ indexes: {
5
+ GSI_TENANT: {
6
+ partitionKey: "GSI_TENANT"
7
+ }
8
+ },
9
+ documentClient
10
+ });
11
+ export { createOpenSearchTable };
12
+
13
+ //# sourceMappingURL=table.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db/table.js","sources":["../../src/db/table.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { createTable, type ITable } from \"@webiny/db-dynamodb\";\n\nexport interface ICreateOpenSearchTableParams {\n name?: string;\n documentClient: DynamoDBDocument;\n}\n\nexport const createOpenSearchTable = ({\n name,\n documentClient\n}: ICreateOpenSearchTableParams): ITable => {\n return createTable({\n name: name || (process.env.DB_TABLE_OPENSEARCH as string),\n indexes: {\n GSI_TENANT: {\n partitionKey: \"GSI_TENANT\"\n }\n },\n documentClient\n });\n};\n"],"names":["createOpenSearchTable","name","documentClient","createTable","process"],"mappings":";AAQO,MAAMA,wBAAwB,CAAC,EAClCC,IAAI,EACJC,cAAc,EACa,GACpBC,YAAY;QACf,MAAMF,QAASG,QAAQ,GAAG,CAAC,mBAAmB;QAC9C,SAAS;YACL,YAAY;gBACR,cAAc;YAClB;QACJ;QACAF;IACJ"}
package/db/types.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import type { IEntity, IStandardEntityAttributes } from "@webiny/db-dynamodb";
2
+ import type { GenericRecord } from "@webiny/api/types.js";
3
+ export interface IOpenSearchEntityAttributes extends IStandardEntityAttributes<GenericRecord> {
4
+ index: string;
5
+ }
6
+ export type IOpenSearchEntity = IEntity<IOpenSearchEntityAttributes>;
package/db/types.js ADDED
File without changes
@@ -0,0 +1,9 @@
1
+ import { OpenSearchClientFactory as OpenSearchClientFactoryAbstraction } from "@webiny/api-opensearch/features/OpenSearchClientFactory/abstraction.js";
2
+ import type { Client, OpenSearchClientOptions } from "@webiny/api-opensearch";
3
+ declare class AwsOpenSearchClientFactoryImpl implements OpenSearchClientFactoryAbstraction.Interface {
4
+ getClient(params: OpenSearchClientOptions): Client;
5
+ }
6
+ export declare const AwsOpenSearchClientFactory: typeof AwsOpenSearchClientFactoryImpl & {
7
+ __abstraction: import("@webiny/di").Abstraction<import("@webiny/api-opensearch/features/OpenSearchClientFactory/abstraction.js").IOpenSearchClientFactory>;
8
+ };
9
+ export {};
@@ -0,0 +1,15 @@
1
+ import { OpenSearchClientFactory } from "@webiny/api-opensearch/features/OpenSearchClientFactory/abstraction.js";
2
+ import { createAwsOpenSearchClient } from "../../createAwsOpenSearchClient.js";
3
+ class AwsOpenSearchClientFactoryImpl {
4
+ getClient(params) {
5
+ if (!params.endpoint && !params.node && !params.nodes) throw new Error("OpenSearch client requires an endpoint, nodes or node to be specified.");
6
+ return createAwsOpenSearchClient(params);
7
+ }
8
+ }
9
+ const AwsOpenSearchClientFactory = OpenSearchClientFactory.createImplementation({
10
+ implementation: AwsOpenSearchClientFactoryImpl,
11
+ dependencies: []
12
+ });
13
+ export { AwsOpenSearchClientFactory };
14
+
15
+ //# sourceMappingURL=AwsOpenSearchClientFactory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"features/AwsOpenSearchClientFactory/AwsOpenSearchClientFactory.js","sources":["../../../src/features/AwsOpenSearchClientFactory/AwsOpenSearchClientFactory.ts"],"sourcesContent":["import { OpenSearchClientFactory as OpenSearchClientFactoryAbstraction } from \"@webiny/api-opensearch/features/OpenSearchClientFactory/abstraction.js\";\nimport type { Client, OpenSearchClientOptions } from \"@webiny/api-opensearch\";\nimport { createAwsOpenSearchClient } from \"~/createAwsOpenSearchClient.js\";\n\nclass AwsOpenSearchClientFactoryImpl implements OpenSearchClientFactoryAbstraction.Interface {\n public getClient(params: OpenSearchClientOptions): Client {\n if (!params.endpoint && !params.node && !params.nodes) {\n throw new Error(\n \"OpenSearch client requires an endpoint, nodes or node to be specified.\"\n );\n }\n return createAwsOpenSearchClient(params);\n }\n}\n\nexport const AwsOpenSearchClientFactory = OpenSearchClientFactoryAbstraction.createImplementation({\n implementation: AwsOpenSearchClientFactoryImpl,\n dependencies: []\n});\n"],"names":["AwsOpenSearchClientFactoryImpl","params","Error","createAwsOpenSearchClient","AwsOpenSearchClientFactory","OpenSearchClientFactoryAbstraction"],"mappings":";;AAIA,MAAMA;IACK,UAAUC,MAA+B,EAAU;QACtD,IAAI,CAACA,OAAO,QAAQ,IAAI,CAACA,OAAO,IAAI,IAAI,CAACA,OAAO,KAAK,EACjD,MAAM,IAAIC,MACN;QAGR,OAAOC,0BAA0BF;IACrC;AACJ;AAEO,MAAMG,6BAA6BC,wBAAAA,oBAAuD,CAAC;IAC9F,gBAAgBL;IAChB,cAAc,EAAE;AACpB"}
@@ -0,0 +1,4 @@
1
+ export declare const AwsOpenSearchClientFactoryFeature: {
2
+ name: string;
3
+ register(container: import("@webiny/di").Container): void;
4
+ };
@@ -0,0 +1,11 @@
1
+ import { createFeature } from "@webiny/feature/api/index.js";
2
+ import { AwsOpenSearchClientFactory } from "./AwsOpenSearchClientFactory.js";
3
+ const AwsOpenSearchClientFactoryFeature = createFeature({
4
+ name: "opensearch.aws.clientFactory",
5
+ register (container) {
6
+ container.register(AwsOpenSearchClientFactory).inSingletonScope();
7
+ }
8
+ });
9
+ export { AwsOpenSearchClientFactoryFeature };
10
+
11
+ //# sourceMappingURL=feature.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"features/AwsOpenSearchClientFactory/feature.js","sources":["../../../src/features/AwsOpenSearchClientFactory/feature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api/index.js\";\nimport { AwsOpenSearchClientFactory } from \"./AwsOpenSearchClientFactory.js\";\n\nexport const AwsOpenSearchClientFactoryFeature = createFeature({\n name: \"opensearch.aws.clientFactory\",\n register(container) {\n container.register(AwsOpenSearchClientFactory).inSingletonScope();\n }\n});\n"],"names":["AwsOpenSearchClientFactoryFeature","createFeature","container","AwsOpenSearchClientFactory"],"mappings":";;AAGO,MAAMA,oCAAoCC,cAAc;IAC3D,MAAM;IACN,UAASC,SAAS;QACdA,UAAU,QAAQ,CAACC,4BAA4B,gBAAgB;IACnE;AACJ"}
package/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { AwsOpenSearchClientFactoryFeature } from "./features/AwsOpenSearchClientFactory/feature.js";
2
+ export { createAwsOpenSearchClient } from "./createAwsOpenSearchClient.js";
3
+ export { createOpenSearchEntity, createOpenSearchTable } from "./db/index.js";
4
+ export type { ICreateOpenSearchEntityParams, ICreateOpenSearchTableParams, IOpenSearchEntity, IOpenSearchEntityAttributes } from "./db/index.js";
package/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { AwsOpenSearchClientFactoryFeature } from "./features/AwsOpenSearchClientFactory/feature.js";
2
+ export { createAwsOpenSearchClient } from "./createAwsOpenSearchClient.js";
3
+ export { createOpenSearchEntity, createOpenSearchTable } from "./db/index.js";
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@webiny/api-opensearch-aws",
3
+ "version": "0.0.0-unstable.0156a4c312",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./index.js",
7
+ "./*": "./*"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/webiny/webiny-js.git",
12
+ "directory": "packages/api-opensearch-aws"
13
+ },
14
+ "description": "AWS-specific OpenSearch client factory for Webiny.",
15
+ "license": "MIT",
16
+ "dependencies": {
17
+ "@opensearch-project/opensearch": "3.9.0",
18
+ "@webiny/api": "0.0.0-unstable.0156a4c312",
19
+ "@webiny/api-opensearch": "0.0.0-unstable.0156a4c312",
20
+ "@webiny/aws-sdk": "0.0.0-unstable.0156a4c312",
21
+ "@webiny/db-dynamodb": "0.0.0-unstable.0156a4c312",
22
+ "@webiny/error": "0.0.0-unstable.0156a4c312",
23
+ "@webiny/feature": "0.0.0-unstable.0156a4c312"
24
+ },
25
+ "devDependencies": {
26
+ "@webiny/build-tools": "0.0.0-unstable.0156a4c312",
27
+ "rimraf": "6.1.3",
28
+ "typescript": "7.0.2",
29
+ "vitest": "5.0.5"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "webiny": {
35
+ "publishFrom": "dist"
36
+ }
37
+ }
@@ -0,0 +1,2 @@
1
+ export { simulateStream } from "./simulateStream.js";
2
+ export { createDynamoStreamEvent, createDynamoStreamRecord } from "./processing.js";
@@ -0,0 +1,2 @@
1
+ export { simulateStream } from "./simulateStream.js";
2
+ export { createDynamoStreamEvent, createDynamoStreamRecord } from "./processing.js";
@@ -0,0 +1,29 @@
1
+ import type { DynamoDBDocument } from "@webiny/aws-sdk/client-dynamodb/index.js";
2
+ export declare const createDynamoStreamEvent: (...records: Record<string, unknown>[]) => {
3
+ Records: Record<string, unknown>[];
4
+ };
5
+ export declare const createDynamoStreamRecord: (eventName: string, data?: {
6
+ Keys?: Record<string, unknown>;
7
+ NewImage?: Record<string, unknown>;
8
+ OldImage?: Record<string, unknown>;
9
+ }) => {
10
+ eventID: string;
11
+ eventName: string;
12
+ eventVersion: string;
13
+ eventSource: string;
14
+ awsRegion: string;
15
+ dynamodb: {
16
+ ApproximateCreationDateTime: number;
17
+ Keys: Record<string, import("@aws-sdk/client-dynamodb").AttributeValue>;
18
+ NewImage: Record<string, import("@aws-sdk/client-dynamodb").AttributeValue> | undefined;
19
+ OldImage: Record<string, import("@aws-sdk/client-dynamodb").AttributeValue> | undefined;
20
+ SequenceNumber: string;
21
+ SizeBytes: number;
22
+ StreamViewType: string;
23
+ };
24
+ eventSourceARN: string;
25
+ };
26
+ type StreamHandler = (event: Record<string, unknown>) => Promise<void>;
27
+ export declare const processing: Record<string, (documentClient: DynamoDBDocument, handler: StreamHandler, params: Record<string, any>) => Promise<void>>;
28
+ export declare const getCommandName: (command: unknown) => string | null;
29
+ export {};
@@ -0,0 +1,114 @@
1
+ import { BatchWriteCommand, DeleteCommand, PutCommand, UpdateCommand, marshall } from "@webiny/aws-sdk/client-dynamodb/index.js";
2
+ const streamTableName = process.env.DB_TABLE_OPENSEARCH;
3
+ const isOpenSearchStreamTable = (table)=>table === streamTableName;
4
+ const createMarshalledObject = (target)=>{
5
+ if (!target) return;
6
+ return marshall(target, {
7
+ convertEmptyValues: true,
8
+ removeUndefinedValues: true
9
+ });
10
+ };
11
+ const createDynamoStreamEvent = (...records)=>({
12
+ Records: records
13
+ });
14
+ const createDynamoStreamRecord = (eventName, data = {})=>{
15
+ const { Keys = {}, NewImage = {}, OldImage = {} } = data;
16
+ return {
17
+ eventID: "2cb5ad3ffabca3639e4f7858e3bdd138",
18
+ eventName,
19
+ eventVersion: "1.1",
20
+ eventSource: "aws:dynamodb",
21
+ awsRegion: "eu-central-1",
22
+ dynamodb: {
23
+ ApproximateCreationDateTime: 1613939165,
24
+ Keys: marshall(Keys),
25
+ NewImage: createMarshalledObject(NewImage),
26
+ OldImage: createMarshalledObject(OldImage),
27
+ SequenceNumber: "300000000029551639656",
28
+ SizeBytes: 14,
29
+ StreamViewType: "NEW_AND_OLD_IMAGES"
30
+ },
31
+ eventSourceARN: "arn:aws:dynamodb:eu-central-1:111111111111:table/streams-11111111/stream/2021-02-21T20:12:44.976"
32
+ };
33
+ };
34
+ const processDelete = async (documentClient, handler, params)=>{
35
+ if (false === isOpenSearchStreamTable(params.input?.TableName)) return;
36
+ const { Key, TableName } = params.input;
37
+ const { Item } = await documentClient.get({
38
+ Key,
39
+ TableName
40
+ });
41
+ if (!Item || !Item.index) return;
42
+ const record = createDynamoStreamRecord("REMOVE", {
43
+ Keys: Key,
44
+ OldImage: Item
45
+ });
46
+ const event = createDynamoStreamEvent(record);
47
+ await handler(event);
48
+ };
49
+ const processPut = async (documentClient, handler, params)=>{
50
+ const tableName = params.input?.TableName;
51
+ if (false === isOpenSearchStreamTable(tableName)) return;
52
+ const item = params.input.Item;
53
+ if (!item) return;
54
+ const { PK, SK } = item;
55
+ const record = createDynamoStreamRecord("INSERT", {
56
+ Keys: {
57
+ PK,
58
+ SK
59
+ },
60
+ NewImage: item
61
+ });
62
+ const event = createDynamoStreamEvent(record);
63
+ await handler(event);
64
+ };
65
+ const processBatchWrite = async (documentClient, handler, params)=>{
66
+ const operations = params?.input?.RequestItems?.[streamTableName];
67
+ if (!Array.isArray(operations)) return;
68
+ const records = [];
69
+ for (const operation of operations){
70
+ const { PutRequest, DeleteRequest } = operation;
71
+ if (DeleteRequest) {
72
+ const { Item } = await documentClient.get({
73
+ Key: DeleteRequest.Key,
74
+ TableName: process.env.DB_TABLE_OPENSEARCH
75
+ });
76
+ if (!Item || !Item.index) continue;
77
+ const record = createDynamoStreamRecord("REMOVE", {
78
+ Keys: DeleteRequest.Key,
79
+ OldImage: Item
80
+ });
81
+ records.push(record);
82
+ }
83
+ if (PutRequest) {
84
+ const { Item } = PutRequest;
85
+ const record = createDynamoStreamRecord("INSERT", {
86
+ Keys: {
87
+ PK: Item.PK,
88
+ SK: Item.SK
89
+ },
90
+ NewImage: Item
91
+ });
92
+ records.push(record);
93
+ }
94
+ }
95
+ if (0 === records.length) return;
96
+ await handler(createDynamoStreamEvent(...records));
97
+ };
98
+ const processing = {
99
+ put: processPut,
100
+ update: processPut,
101
+ delete: processDelete,
102
+ batchWrite: processBatchWrite
103
+ };
104
+ const getCommandName = (command)=>{
105
+ if (!command) return null;
106
+ if (command instanceof PutCommand) return "put";
107
+ else if (command instanceof UpdateCommand) return "update";
108
+ else if (command instanceof DeleteCommand) return "delete";
109
+ else if (command instanceof BatchWriteCommand) return "batchWrite";
110
+ return null;
111
+ };
112
+ export { createDynamoStreamEvent, createDynamoStreamRecord, getCommandName, processing };
113
+
114
+ //# sourceMappingURL=processing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing/processing.js","sources":["../../src/testing/processing.ts"],"sourcesContent":["import { marshall } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { PutCommand } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { UpdateCommand } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { DeleteCommand } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { BatchWriteCommand } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\n\nconst streamTableName = process.env.DB_TABLE_OPENSEARCH;\n\nconst isOpenSearchStreamTable = (table: string) => {\n return table === streamTableName;\n};\n\nconst createMarshalledObject = (target: Record<string, unknown> | undefined) => {\n if (!target) {\n return undefined;\n }\n return marshall(target, {\n convertEmptyValues: true,\n removeUndefinedValues: true\n });\n};\n\nexport const createDynamoStreamEvent = (...records: Record<string, unknown>[]) => {\n return { Records: records };\n};\n\nexport const createDynamoStreamRecord = (\n eventName: string,\n data: {\n Keys?: Record<string, unknown>;\n NewImage?: Record<string, unknown>;\n OldImage?: Record<string, unknown>;\n } = {}\n) => {\n const { Keys = {}, NewImage = {}, OldImage = {} } = data;\n return {\n eventID: \"2cb5ad3ffabca3639e4f7858e3bdd138\",\n eventName,\n eventVersion: \"1.1\",\n eventSource: \"aws:dynamodb\",\n awsRegion: \"eu-central-1\",\n dynamodb: {\n ApproximateCreationDateTime: 1613939165,\n Keys: marshall(Keys),\n NewImage: createMarshalledObject(NewImage),\n OldImage: createMarshalledObject(OldImage),\n SequenceNumber: \"300000000029551639656\",\n SizeBytes: 14,\n StreamViewType: \"NEW_AND_OLD_IMAGES\"\n },\n eventSourceARN:\n \"arn:aws:dynamodb:eu-central-1:111111111111:table/streams-11111111/stream/2021-02-21T20:12:44.976\"\n };\n};\n\ntype StreamHandler = (event: Record<string, unknown>) => Promise<void>;\n\nconst processDelete = async (\n documentClient: DynamoDBDocument,\n handler: StreamHandler,\n params: Record<string, any>\n) => {\n if (isOpenSearchStreamTable(params.input?.TableName) === false) {\n return;\n }\n const { Key, TableName } = params.input;\n const { Item } = await documentClient.get({ Key, TableName });\n\n if (!Item || !Item.index) {\n return;\n }\n const record = createDynamoStreamRecord(\"REMOVE\", { Keys: Key, OldImage: Item });\n const event = createDynamoStreamEvent(record);\n\n await handler(event);\n};\n\nconst processPut = async (\n documentClient: DynamoDBDocument,\n handler: StreamHandler,\n params: Record<string, any>\n) => {\n const tableName = params.input?.TableName;\n if (isOpenSearchStreamTable(tableName) === false) {\n return;\n }\n\n const item = params.input.Item;\n if (!item) {\n return;\n }\n const { PK, SK } = item;\n\n const record = createDynamoStreamRecord(\"INSERT\", { Keys: { PK, SK }, NewImage: item });\n const event = createDynamoStreamEvent(record);\n\n await handler(event);\n};\n\nconst processBatchWrite = async (\n documentClient: DynamoDBDocument,\n handler: StreamHandler,\n params: Record<string, any>\n) => {\n const operations = params?.input?.RequestItems?.[streamTableName!];\n if (!Array.isArray(operations)) {\n return;\n }\n\n const records = [];\n for (const operation of operations) {\n const { PutRequest, DeleteRequest } = operation;\n if (DeleteRequest) {\n const { Item } = await documentClient.get({\n Key: DeleteRequest.Key,\n TableName: process.env.DB_TABLE_OPENSEARCH\n });\n\n // A missing record (or one without an index) emits no REMOVE record, like DynamoDB\n // streams for a delete of a missing item and like `processDelete`.\n if (!Item || !Item.index) {\n continue;\n }\n const record = createDynamoStreamRecord(\"REMOVE\", {\n Keys: DeleteRequest.Key,\n OldImage: Item\n });\n records.push(record);\n }\n\n if (PutRequest) {\n const { Item } = PutRequest;\n const record = createDynamoStreamRecord(\"INSERT\", {\n Keys: { PK: Item.PK, SK: Item.SK },\n NewImage: Item\n });\n records.push(record);\n }\n }\n if (records.length === 0) {\n return;\n }\n await handler(createDynamoStreamEvent(...records));\n};\n\nexport const processing: Record<\n string,\n (\n documentClient: DynamoDBDocument,\n handler: StreamHandler,\n params: Record<string, any>\n ) => Promise<void>\n> = {\n put: processPut,\n update: processPut,\n delete: processDelete,\n batchWrite: processBatchWrite\n};\n\nexport const getCommandName = (command: unknown): string | null => {\n if (!command) {\n return null;\n }\n if (command instanceof PutCommand) {\n return \"put\";\n } else if (command instanceof UpdateCommand) {\n return \"update\";\n } else if (command instanceof DeleteCommand) {\n return \"delete\";\n } else if (command instanceof BatchWriteCommand) {\n return \"batchWrite\";\n }\n return null;\n};\n"],"names":["streamTableName","process","isOpenSearchStreamTable","table","createMarshalledObject","target","marshall","createDynamoStreamEvent","records","createDynamoStreamRecord","eventName","data","Keys","NewImage","OldImage","processDelete","documentClient","handler","params","Key","TableName","Item","record","event","processPut","tableName","item","PK","SK","processBatchWrite","operations","Array","operation","PutRequest","DeleteRequest","processing","getCommandName","command","PutCommand","UpdateCommand","DeleteCommand","BatchWriteCommand"],"mappings":"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"}
@@ -0,0 +1,4 @@
1
+ import type { DynamoDBDocument } from "@webiny/aws-sdk/client-dynamodb/index.js";
2
+ export { createDynamoStreamEvent, createDynamoStreamRecord } from "./processing.js";
3
+ type StreamHandler = (event: Record<string, unknown>) => Promise<void>;
4
+ export declare const simulateStream: (documentClient: DynamoDBDocument, handler: StreamHandler) => void;
@@ -0,0 +1,21 @@
1
+ import { createDynamoStreamEvent, createDynamoStreamRecord, getCommandName, processing } from "./processing.js";
2
+ const simulateStream = (documentClient, handler)=>{
3
+ const originalSend = documentClient["send"];
4
+ documentClient.send = async (...params)=>{
5
+ const [command] = params;
6
+ const name = getCommandName(command);
7
+ if (name) {
8
+ if (!processing[name]) throw new Error(`Missing handler for "${name}" command.`);
9
+ try {
10
+ await processing[name](documentClient, handler, command);
11
+ } catch (ex) {
12
+ console.log(JSON.stringify(command));
13
+ throw new Error(`Error processing "${name}" command: ${ex.message}`, ex);
14
+ }
15
+ }
16
+ return await originalSend.apply(documentClient, params);
17
+ };
18
+ };
19
+ export { createDynamoStreamEvent, createDynamoStreamRecord, simulateStream };
20
+
21
+ //# sourceMappingURL=simulateStream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing/simulateStream.js","sources":["../../src/testing/simulateStream.ts"],"sourcesContent":["import type { DynamoDBDocument } from \"@webiny/aws-sdk/client-dynamodb/index.js\";\nimport { processing, getCommandName } from \"./processing.js\";\nexport { createDynamoStreamEvent, createDynamoStreamRecord } from \"./processing.js\";\n\ntype StreamHandler = (event: Record<string, unknown>) => Promise<void>;\n\nexport const simulateStream = (documentClient: DynamoDBDocument, handler: StreamHandler) => {\n const originalSend = documentClient[\"send\"];\n documentClient.send = async (...params: any[]) => {\n const [command] = params;\n\n const name = getCommandName(command);\n if (name) {\n if (!processing[name]) {\n throw new Error(`Missing handler for \"${name}\" command.`);\n }\n try {\n await processing[name](documentClient, handler, command);\n } catch (ex: any) {\n console.log(JSON.stringify(command));\n throw new Error(`Error processing \"${name}\" command: ${ex.message}`, ex);\n }\n }\n\n return await originalSend.apply(documentClient, params as any);\n };\n};\n"],"names":["simulateStream","documentClient","handler","originalSend","params","command","name","getCommandName","processing","Error","ex","console","JSON"],"mappings":";AAMO,MAAMA,iBAAiB,CAACC,gBAAkCC;IAC7D,MAAMC,eAAeF,cAAc,CAAC,OAAO;IAC3CA,eAAe,IAAI,GAAG,OAAO,GAAGG;QAC5B,MAAM,CAACC,QAAQ,GAAGD;QAElB,MAAME,OAAOC,eAAeF;QAC5B,IAAIC,MAAM;YACN,IAAI,CAACE,UAAU,CAACF,KAAK,EACjB,MAAM,IAAIG,MAAM,CAAC,qBAAqB,EAAEH,KAAK,UAAU,CAAC;YAE5D,IAAI;gBACA,MAAME,UAAU,CAACF,KAAK,CAACL,gBAAgBC,SAASG;YACpD,EAAE,OAAOK,IAAS;gBACdC,QAAQ,GAAG,CAACC,KAAK,SAAS,CAACP;gBAC3B,MAAM,IAAII,MAAM,CAAC,kBAAkB,EAAEH,KAAK,WAAW,EAAEI,GAAG,OAAO,EAAE,EAAEA;YACzE;QACJ;QAEA,OAAO,MAAMP,aAAa,KAAK,CAACF,gBAAgBG;IACpD;AACJ"}