@randstad-uca/aws-sns-publisher 1.2.2 → 1.2.4

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.
@@ -32,6 +32,7 @@ export declare const validEventTypes: {
32
32
  push: string;
33
33
  addUserIdentity: string;
34
34
  deleteOneSignalUser: string;
35
+ customEvents: string;
35
36
  };
36
37
  export declare const validDocumentStatus: {
37
38
  enviado: string;
@@ -35,6 +35,7 @@ exports.validEventTypes = {
35
35
  push: 'push',
36
36
  addUserIdentity: 'add-user-identity',
37
37
  deleteOneSignalUser: 'delete-one-signal-user',
38
+ customEvents: 'custom-events',
38
39
  };
39
40
  exports.validDocumentStatus = {
40
41
  enviado: 'enviado',
@@ -21,6 +21,7 @@ const push_schema_1 = require("./schemas/push.schema");
21
21
  const cv_schema_1 = require("./schemas/cv.schema");
22
22
  const user_identity_schema_1 = require("./schemas/user-identity.schema");
23
23
  const one_signal_schema_1 = require("./schemas/one-signal.schema");
24
+ const custom_events_schema_1 = require("./schemas/custom-events.schema");
24
25
  const schemas = {
25
26
  [constants_1.validEventTypes.sms]: { schema: sms_schema_1.SMSSchema, label: 'SMS' },
26
27
  [constants_1.validEventTypes.updatePersonalData]: {
@@ -119,6 +120,10 @@ const schemas = {
119
120
  schema: one_signal_schema_1.DeleteOneSignalUserSchema,
120
121
  label: 'Delete OneSignal User',
121
122
  },
123
+ [constants_1.validEventTypes.customEvents]: {
124
+ schema: custom_events_schema_1.CustomEventsSchema,
125
+ label: 'Custom Events',
126
+ },
122
127
  };
123
128
  function getFieldsFromJoi(schema) {
124
129
  const description = schema.describe();
@@ -0,0 +1,2 @@
1
+ import Joi from 'joi';
2
+ export declare const CustomEventsSchema: Joi.ArraySchema<any[]>;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CustomEventsSchema = void 0;
7
+ const joi_1 = __importDefault(require("joi"));
8
+ const CustomEventItemSchema = joi_1.default.object({
9
+ name: joi_1.default.string().required(),
10
+ external_id: joi_1.default.string().uuid().required(),
11
+ properties: joi_1.default.object().pattern(joi_1.default.string(), joi_1.default.string()).optional(),
12
+ idempotency_key: joi_1.default.string().uuid().optional(),
13
+ }).unknown(false);
14
+ exports.CustomEventsSchema = joi_1.default.array()
15
+ .items(CustomEventItemSchema)
16
+ .min(1)
17
+ .required()
18
+ .meta({ className: 'CustomEventsType' });
@@ -1,5 +1,6 @@
1
1
  export * from './alert.schema';
2
2
  export * from './certifications.schema';
3
+ export * from './custom-events.schema';
3
4
  export * from './update-documents-status.schema';
4
5
  export * from './education.schema';
5
6
  export * from './email.schema';
@@ -16,6 +16,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./alert.schema"), exports);
18
18
  __exportStar(require("./certifications.schema"), exports);
19
+ __exportStar(require("./custom-events.schema"), exports);
19
20
  __exportStar(require("./update-documents-status.schema"), exports);
20
21
  __exportStar(require("./education.schema"), exports);
21
22
  __exportStar(require("./email.schema"), exports);
@@ -0,0 +1,12 @@
1
+ /**
2
+ * This file was automatically generated by joi-to-typescript
3
+ * Do not modify this file manually
4
+ */
5
+ export interface CustomEventItem {
6
+ name: string;
7
+ external_id: string;
8
+ properties: {
9
+ [key: string]: string;
10
+ };
11
+ }
12
+ export type CustomEventsType = CustomEventItem[];
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ /**
3
+ * This file was automatically generated by joi-to-typescript
4
+ * Do not modify this file manually
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -4,6 +4,7 @@
4
4
  */
5
5
  export * from './alert.type';
6
6
  export * from './certifications.type';
7
+ export * from './custom-events.type';
7
8
  export * from './cv.type';
8
9
  export * from './education.type';
9
10
  export * from './email.type';
@@ -20,6 +20,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
21
  __exportStar(require("./alert.type"), exports);
22
22
  __exportStar(require("./certifications.type"), exports);
23
+ __exportStar(require("./custom-events.type"), exports);
23
24
  __exportStar(require("./cv.type"), exports);
24
25
  __exportStar(require("./education.type"), exports);
25
26
  __exportStar(require("./email.type"), exports);
@@ -17,6 +17,7 @@ const cv_schema_1 = require("./schemas/cv.schema");
17
17
  const update_documents_status_schema_1 = require("./schemas/update-documents-status.schema");
18
18
  const user_identity_schema_1 = require("./schemas/user-identity.schema");
19
19
  const one_signal_schema_1 = require("./schemas/one-signal.schema");
20
+ const custom_events_schema_1 = require("./schemas/custom-events.schema");
20
21
  const validateSchema = (eventType, data) => {
21
22
  let schema;
22
23
  switch (eventType) {
@@ -94,6 +95,9 @@ const validateSchema = (eventType, data) => {
94
95
  case constants_1.validEventTypes.deleteOneSignalUser:
95
96
  schema = one_signal_schema_1.DeleteOneSignalUserSchema;
96
97
  break;
98
+ case constants_1.validEventTypes.customEvents:
99
+ schema = custom_events_schema_1.CustomEventsSchema;
100
+ break;
97
101
  default:
98
102
  console.error(`Unknown event type: ${eventType}`);
99
103
  return false;
package/package.json CHANGED
@@ -1,50 +1,50 @@
1
- {
2
- "name": "@randstad-uca/aws-sns-publisher",
3
- "version": "1.2.2",
4
- "description": "AWS SNS Publisher",
5
- "main": "./build/index.js",
6
- "types": "./build/index.d.ts",
7
- "files": [
8
- "build/**/*",
9
- "schema-doc.md"
10
- ],
11
- "scripts": {
12
- "clean": "rimraf build",
13
- "build": "npm run clean && npx tsc",
14
- "test": "echo \"No tests implemented yet\" && exit 0",
15
- "prepublishOnly": "npm run test && npm run generate-types && npm run generate-doc && npm run build",
16
- "pub": "npm publish",
17
- "generate-doc": "ts-node ./src/generate-schema-doc.ts",
18
- "generate-types": "ts-node ./src/generate-types.ts"
19
- },
20
- "keywords": [
21
- "aws",
22
- "sns",
23
- "publisher"
24
- ],
25
- "author": "Facundo Brusa",
26
- "repository": {
27
- "type": "git",
28
- "url": "git+https://github.com/randstad-argentina/aws-sns-publisher.git"
29
- },
30
- "bugs": {
31
- "url": "https://github.com/randstad-argentina/aws-sns-publisher/issues"
32
- },
33
- "homepage": "https://github.com/randstad-argentina/aws-sns-publisher#readme",
34
- "license": "ISC",
35
- "publishConfig": {
36
- "access": "public"
37
- },
38
- "devDependencies": {
39
- "@types/node": "^22.15.17",
40
- "joi-to-typescript": "^4.15.0",
41
- "rimraf": "^6.0.1",
42
- "ts-node": "^10.9.2",
43
- "typescript": "^5.7.3"
44
- },
45
- "dependencies": {
46
- "@aws-sdk/client-sns": "^3.741.0",
47
- "joi": "^17.13.3",
48
- "uuid": "^11.0.5"
49
- }
50
- }
1
+ {
2
+ "name": "@randstad-uca/aws-sns-publisher",
3
+ "version": "1.2.4",
4
+ "description": "AWS SNS Publisher",
5
+ "main": "./build/index.js",
6
+ "types": "./build/index.d.ts",
7
+ "files": [
8
+ "build/**/*",
9
+ "schema-doc.md"
10
+ ],
11
+ "scripts": {
12
+ "clean": "rimraf build",
13
+ "build": "npm run clean && npx tsc",
14
+ "test": "echo \"No tests implemented yet\" && exit 0",
15
+ "prepublishOnly": "npm run test && npm run generate-types && npm run generate-doc && npm run build",
16
+ "pub": "npm publish",
17
+ "generate-doc": "ts-node ./src/generate-schema-doc.ts",
18
+ "generate-types": "ts-node ./src/generate-types.ts"
19
+ },
20
+ "keywords": [
21
+ "aws",
22
+ "sns",
23
+ "publisher"
24
+ ],
25
+ "author": "Facundo Brusa",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/randstad-argentina/aws-sns-publisher.git"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/randstad-argentina/aws-sns-publisher/issues"
32
+ },
33
+ "homepage": "https://github.com/randstad-argentina/aws-sns-publisher#readme",
34
+ "license": "ISC",
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^22.15.17",
40
+ "joi-to-typescript": "^4.15.0",
41
+ "rimraf": "^6.0.1",
42
+ "ts-node": "^10.9.2",
43
+ "typescript": "^5.7.3"
44
+ },
45
+ "dependencies": {
46
+ "@aws-sdk/client-sns": "^3.741.0",
47
+ "joi": "^17.13.3",
48
+ "uuid": "^11.0.5"
49
+ }
50
+ }
package/readme.md CHANGED
@@ -1,156 +1,156 @@
1
- # @randstad-uca/aws-sns-publisher
2
-
3
- ---
4
-
5
- Es una librería ligera desarrollada en Node.js para publicar mensajes a Amazon SNS de forma simple, validada y con logging configurable. Ideal para sistemas desacoplados y orientados a eventos en entornos AWS.
6
-
7
- ---
8
-
9
- ## 📦 Instalación
10
-
11
- ```bash
12
- npm install @randstad-uca/aws-sns-publisher
13
- ```
14
-
15
- ---
16
-
17
- ## 🚀 Uso Básico
18
-
19
- ```js
20
- import { SimpleSNSPublisher } from '@randstad-uca/aws-sns-publisher';
21
-
22
- const SNSClient = new SimpleSNSPublisher({
23
- awsConfig: { region: 'us-east-1' }, // required obj
24
- logEnabled: true, // optional (default value: true)
25
- logLevel: 'info', // optional (default value: info)
26
- throwError: true, // optional (default value: true)
27
- logHandler: {
28
- // You can implement your own logging handler here (optional)
29
- info: (args) =>
30
- // success case
31
- console.log('Custom success logging handler logic', args),
32
- error: (args) =>
33
- // error case
34
- console.error('Custom error logging handler logic', args),
35
- },
36
- });
37
-
38
- const payload = {
39
- eventType: 'sms',
40
- payload: {
41
- phone: '+543564123123',
42
- message: 'Hello there!',
43
- },
44
- };
45
-
46
- SNSClient.publish({
47
- message: JSON.stringify(payload),
48
- topicARN: 'your-sns-topic-ARN',
49
- apiName: 'api-name', // If the topic type is FIFO you must define a valid apiName
50
- })
51
- .then((result) => console.log('Success:', result))
52
- .catch((err) => console.error('Error:', err));
53
- ```
54
-
55
- ---
56
-
57
- ## 📘 API
58
-
59
- #### Clase: `SimpleSNSPublisher`
60
-
61
- ##### Constructor
62
- ```js
63
- new SimpleSNSPublisher(options: IPublisherOptions)
64
- ```
65
-
66
- `IPublisherOptions:`
67
-
68
- - `awsConfig: SNSClientConfig` – **Requerido**. Como minimo se debe especificar la región de AWS para instanciar el cliente SNS.
69
-
70
- - `logEnabled?: boolean` – Habilita logs. Default: `true`.
71
-
72
- - `logLevel?: 'info' | 'silent'` – Nivel de log. Default: `'info'`.
73
-
74
- - `throwError?: boolean` – Si lanzar errores o no. Default: `true`.
75
-
76
- - `logHandler?: { info: Function; error: Function }` – Handler personalizado para logs.
77
-
78
- ---
79
-
80
- ## ✨ Metodos
81
-
82
- #### Método: `publish(options: IPublishOptions): Promise<PublishResponse>`
83
-
84
- Publica un mensaje en un topic SNS. Antes de enviar el mensaje, se valida su estructura usando la libreria `Joi`.
85
-
86
- `IPublishOptions`:
87
-
88
- - `message: string` – Debe ser un string que contenga un objeto, y este **debe** tener las siguientes propiedades:
89
-
90
- - `eventType: string` – Tipo del evento (ej: `"sms"`, `"add-personal-data"` o cualquiera que se encuentre dentro del objeto ***validEventTypes*** ubicado en el archivo `constants.ts`).
91
-
92
- - `payload: object` – Objeto con los datos del evento.
93
-
94
- - `topicARN: string` – ARN del SNS Topic.
95
-
96
- - `apiName?: string` – Nombre de la API emisora, las unicas validas son las que se encuentran dentro del objeto ***validApiNames*** ubicado en el archivo `constants.ts`.
97
- <span style="color: red;">Esta se utiliza como bandera para la creación del MessageDeduplicationId y MessageGroupId necesarios en topics FIFO.</span>
98
-
99
-
100
- - `extraOptions?: object` – Parámetros adicionales para `PublishCommand`.
101
-
102
- **Validaciones automáticas:**
103
-
104
- - `eventType` es obligatorio y debe estar en la lista de eventos válidos.
105
-
106
- - Se valida el `payload` según el tipo de evento con esquemas Joi definidos internamente.
107
-
108
- - Si se configura `throwError: true`, lanza error. Si no, devuelve `Promise.reject()` con el error.
109
-
110
-
111
- #### Método: `validateSchema(eventType: string, payload: object): boolean`
112
-
113
- Valida el `payload` contra el esquema correspondiente según eventType.
114
-
115
- ---
116
-
117
- ### 📎 Ejemplo de payload válido
118
-
119
- ```json
120
- {
121
- "eventType": "email",
122
- "payload": {
123
- "to": "user@example.com",
124
- "subject": "Hello!",
125
- "body": "This is an example email."
126
- }
127
- }
128
- ```
129
-
130
- ---
131
-
132
- ## 📄 Schema Documentation
133
-
134
- See [schema-doc.md](./schema-doc.md) for a full list of event types and their schema fields
135
-
136
- ---
137
-
138
- 🧩 Características
139
-
140
- - ✅ Compatible con múltiples regiones AWS.
141
-
142
- - ✅ Validación automática con Joi.
143
-
144
- - ✅ Logging personalizable (info y error).
145
-
146
- - ✅ Ideal para arquitectura orientada a eventos.
147
-
148
- ---
149
-
150
- 📌 Consideraciones
151
-
152
- - Se espera que los topics estén previamente creados en SNS.
153
-
154
- - Esta librería no crea los topics automáticamente.
155
-
156
- - <span style="color:red">En caso de usar topics FIFO, es importante pasar un `apiName` **valido** para deduplicación.</span>
1
+ # @randstad-uca/aws-sns-publisher
2
+
3
+ ---
4
+
5
+ Es una librería ligera desarrollada en Node.js para publicar mensajes a Amazon SNS de forma simple, validada y con logging configurable. Ideal para sistemas desacoplados y orientados a eventos en entornos AWS.
6
+
7
+ ---
8
+
9
+ ## 📦 Instalación
10
+
11
+ ```bash
12
+ npm install @randstad-uca/aws-sns-publisher
13
+ ```
14
+
15
+ ---
16
+
17
+ ## 🚀 Uso Básico
18
+
19
+ ```js
20
+ import { SimpleSNSPublisher } from '@randstad-uca/aws-sns-publisher';
21
+
22
+ const SNSClient = new SimpleSNSPublisher({
23
+ awsConfig: { region: 'us-east-1' }, // required obj
24
+ logEnabled: true, // optional (default value: true)
25
+ logLevel: 'info', // optional (default value: info)
26
+ throwError: true, // optional (default value: true)
27
+ logHandler: {
28
+ // You can implement your own logging handler here (optional)
29
+ info: (args) =>
30
+ // success case
31
+ console.log('Custom success logging handler logic', args),
32
+ error: (args) =>
33
+ // error case
34
+ console.error('Custom error logging handler logic', args),
35
+ },
36
+ });
37
+
38
+ const payload = {
39
+ eventType: 'sms',
40
+ payload: {
41
+ phone: '+543564123123',
42
+ message: 'Hello there!',
43
+ },
44
+ };
45
+
46
+ SNSClient.publish({
47
+ message: JSON.stringify(payload),
48
+ topicARN: 'your-sns-topic-ARN',
49
+ apiName: 'api-name', // If the topic type is FIFO you must define a valid apiName
50
+ })
51
+ .then((result) => console.log('Success:', result))
52
+ .catch((err) => console.error('Error:', err));
53
+ ```
54
+
55
+ ---
56
+
57
+ ## 📘 API
58
+
59
+ #### Clase: `SimpleSNSPublisher`
60
+
61
+ ##### Constructor
62
+ ```js
63
+ new SimpleSNSPublisher(options: IPublisherOptions)
64
+ ```
65
+
66
+ `IPublisherOptions:`
67
+
68
+ - `awsConfig: SNSClientConfig` – **Requerido**. Como minimo se debe especificar la región de AWS para instanciar el cliente SNS.
69
+
70
+ - `logEnabled?: boolean` – Habilita logs. Default: `true`.
71
+
72
+ - `logLevel?: 'info' | 'silent'` – Nivel de log. Default: `'info'`.
73
+
74
+ - `throwError?: boolean` – Si lanzar errores o no. Default: `true`.
75
+
76
+ - `logHandler?: { info: Function; error: Function }` – Handler personalizado para logs.
77
+
78
+ ---
79
+
80
+ ## ✨ Metodos
81
+
82
+ #### Método: `publish(options: IPublishOptions): Promise<PublishResponse>`
83
+
84
+ Publica un mensaje en un topic SNS. Antes de enviar el mensaje, se valida su estructura usando la libreria `Joi`.
85
+
86
+ `IPublishOptions`:
87
+
88
+ - `message: string` – Debe ser un string que contenga un objeto, y este **debe** tener las siguientes propiedades:
89
+
90
+ - `eventType: string` – Tipo del evento (ej: `"sms"`, `"add-personal-data"` o cualquiera que se encuentre dentro del objeto ***validEventTypes*** ubicado en el archivo `constants.ts`).
91
+
92
+ - `payload: object` – Objeto con los datos del evento.
93
+
94
+ - `topicARN: string` – ARN del SNS Topic.
95
+
96
+ - `apiName?: string` – Nombre de la API emisora, las unicas validas son las que se encuentran dentro del objeto ***validApiNames*** ubicado en el archivo `constants.ts`.
97
+ <span style="color: red;">Esta se utiliza como bandera para la creación del MessageDeduplicationId y MessageGroupId necesarios en topics FIFO.</span>
98
+
99
+
100
+ - `extraOptions?: object` – Parámetros adicionales para `PublishCommand`.
101
+
102
+ **Validaciones automáticas:**
103
+
104
+ - `eventType` es obligatorio y debe estar en la lista de eventos válidos.
105
+
106
+ - Se valida el `payload` según el tipo de evento con esquemas Joi definidos internamente.
107
+
108
+ - Si se configura `throwError: true`, lanza error. Si no, devuelve `Promise.reject()` con el error.
109
+
110
+
111
+ #### Método: `validateSchema(eventType: string, payload: object): boolean`
112
+
113
+ Valida el `payload` contra el esquema correspondiente según eventType.
114
+
115
+ ---
116
+
117
+ ### 📎 Ejemplo de payload válido
118
+
119
+ ```json
120
+ {
121
+ "eventType": "email",
122
+ "payload": {
123
+ "to": "user@example.com",
124
+ "subject": "Hello!",
125
+ "body": "This is an example email."
126
+ }
127
+ }
128
+ ```
129
+
130
+ ---
131
+
132
+ ## 📄 Schema Documentation
133
+
134
+ See [schema-doc.md](./schema-doc.md) for a full list of event types and their schema fields
135
+
136
+ ---
137
+
138
+ 🧩 Características
139
+
140
+ - ✅ Compatible con múltiples regiones AWS.
141
+
142
+ - ✅ Validación automática con Joi.
143
+
144
+ - ✅ Logging personalizable (info y error).
145
+
146
+ - ✅ Ideal para arquitectura orientada a eventos.
147
+
148
+ ---
149
+
150
+ 📌 Consideraciones
151
+
152
+ - Se espera que los topics estén previamente creados en SNS.
153
+
154
+ - Esta librería no crea los topics automáticamente.
155
+
156
+ - <span style="color:red">En caso de usar topics FIFO, es importante pasar un `apiName` **valido** para deduplicación.</span>