amqp-extension 0.0.1 → 0.0.5

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.
Files changed (52) hide show
  1. package/README.MD +284 -461
  2. package/dist/config/index.d.ts +2 -0
  3. package/dist/config/index.js +15 -0
  4. package/dist/config/index.js.map +1 -0
  5. package/dist/config/type.d.ts +15 -0
  6. package/dist/config/type.js +3 -0
  7. package/dist/config/type.js.map +1 -0
  8. package/dist/config/utils.d.ts +4 -0
  9. package/dist/config/utils.js +39 -0
  10. package/dist/config/utils.js.map +1 -0
  11. package/dist/connection/index.d.ts +1 -0
  12. package/dist/connection/index.js +14 -0
  13. package/dist/connection/index.js.map +1 -0
  14. package/dist/connection/utils.d.ts +6 -0
  15. package/dist/{connection.js → connection/utils.js} +33 -8
  16. package/dist/connection/utils.js.map +1 -0
  17. package/dist/consume/index.d.ts +2 -0
  18. package/dist/consume/index.js +15 -0
  19. package/dist/consume/index.js.map +1 -0
  20. package/dist/consume/type.d.ts +31 -0
  21. package/dist/consume/type.js +3 -0
  22. package/dist/consume/type.js.map +1 -0
  23. package/dist/consume/utils.d.ts +2 -0
  24. package/dist/consume/utils.js +133 -0
  25. package/dist/consume/utils.js.map +1 -0
  26. package/dist/index.d.ts +5 -0
  27. package/dist/index.js +7 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/message/build.d.ts +2 -0
  30. package/dist/message/build.js +16 -0
  31. package/dist/message/build.js.map +1 -0
  32. package/dist/message/index.d.ts +2 -0
  33. package/dist/message/index.js +15 -0
  34. package/dist/message/index.js.map +1 -0
  35. package/dist/message/type.d.ts +46 -0
  36. package/dist/message/type.js +3 -0
  37. package/dist/message/type.js.map +1 -0
  38. package/dist/publish/index.d.ts +2 -0
  39. package/dist/publish/index.js +15 -0
  40. package/dist/publish/index.js.map +1 -0
  41. package/dist/publish/type.d.ts +12 -0
  42. package/dist/publish/type.js +3 -0
  43. package/dist/publish/type.js.map +1 -0
  44. package/dist/publish/utils.d.ts +3 -0
  45. package/dist/publish/utils.js +87 -0
  46. package/dist/publish/utils.js.map +1 -0
  47. package/dist/utils.d.ts +6 -0
  48. package/dist/utils.js +81 -0
  49. package/dist/utils.js.map +1 -0
  50. package/package.json +20 -4
  51. package/dist/connection.d.ts +0 -2
  52. package/dist/connection.js.map +0 -1
package/README.MD CHANGED
@@ -1,27 +1,27 @@
1
1
  [![npm version](https://badge.fury.io/js/amqp-extension.svg)](https://badge.fury.io/js/amqp-extension)
2
- [![codecov](https://codecov.io/gh/Tada5hi/amqp-extension/branch/master/graph/badge.svg?token=4KNSG8L13V)](https://codecov.io/gh/Tada5hi/amqp-extension)
2
+ [![codecov](https://codecov.io/gh/Tada5hi/amqp-extension/branch/master/graph/badge.svg?token=6YELWNP9HG)](https://codecov.io/gh/Tada5hi/amqp-extension)
3
3
  [![Master Workflow](https://github.com/Tada5hi/amqp-extension/workflows/main/badge.svg)](https://github.com/Tada5hi/amqp-extension)
4
- [![Known Vulnerabilities](https://snyk.io/test/github/Tada5hi/amqp-extension/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Tada5hi/amqp-extension?targetFile=package.json)
5
4
 
6
- # AMQP Extension 🚀
5
+ # AMQP Extension 🏰
7
6
 
8
- This is a library on top of the famous `amqplib` and specifies a specific mesasge format for queue message across multiple standalone services.
7
+ This is a library on top of the famous [amqplib](https://www.npmjs.com/package/amqplib) library and defines a [message format](#message-types) for queue messages through a message broker across multiple standalone services.
8
+ All utility functions support the usage of multiple registered connections.
9
9
 
10
10
  **Table of Contents**
11
11
 
12
12
  - [Installation](#installation)
13
13
  - [Usage](#usage)
14
- - Functions(#functions)
15
- - [Connection](#functions---connection)
16
- - [createDatabase](#createConnection)
17
- - [dropDatabase](#useConnection)
18
- - [Query](#functions---query)
19
- - [applyFields](#applyfields)
20
- - [applyFilters](#applyfilters)
21
- - [applyIncludes](#applyincludes)
22
- - [applyPagination](#applypagination)
23
- - [applySort](#applysort)
24
-
14
+ - [Publish](#publish)
15
+ - [Consume](#consume)
16
+ - [Functions](#functions)
17
+ - [useConnection](#useconnection)
18
+ - [publishMessage](#publishmessage)
19
+ - [consumeQueue](#consumequeue)
20
+ - [Types](#types)
21
+ - [Config](#config-types)
22
+ - [Consume](#consume-types)
23
+ - [Message](#message-types)
24
+ - [Publish](#publish-types)
25
25
 
26
26
 
27
27
 
@@ -31,581 +31,404 @@ This is a library on top of the famous `amqplib` and specifies a specific mesasg
31
31
  npm install amqp-extension --save
32
32
  ```
33
33
 
34
- ## Limitations
35
-
36
- At the moment you can only `create` and `drop` a database for one of the following typeorm drivers:
37
- * CockroachDB
38
- * MSSQL
39
- * MySQL
40
- * Oracle
41
- * Postgres
42
- * SQLite
43
-
44
34
  ## Usage
45
35
 
46
- ### CLI
47
-
48
- You can use the following commands in the terminal:
49
- - `amqp-extension db:create` to create the database
50
- - `amqp-extension db:drop` to drop the database
51
-
52
- Alternatively, you can set the full command path in the package.json file and run it f.e. with ts-node.
53
-
54
- ```
55
- "scripts": {
56
- ...
57
- "db:create": "ts-node ./node_modules/amqp-extension/dist/cli/index.js db:create",
58
- "db:drop": "ts-node ./node_modules/amqp-extension/dist/cli/index.js db:drop",
59
- ...
60
- }
61
- ```
62
-
63
- #### CLI Options
64
-
65
- | Option | Default | Description |
66
- | ---------------------- | --------------- | --------------------------------------------------------------------------- |
67
- | `--connection` or `-c` | `default` | Name of the typeorm connection. Required if there are multiple connections. |
68
- | `--config` or `-f` | `ormconfig.js` | Name to the typeorm config file. |
69
- | `--root` or `-r` | `process.cwd()` | Path to the typeorm config file. |
70
- | `--synchronize` or `-s`| `yes` | Synchronize the database schema after database creation. This option is only available for the create command. Options: `yes` or `no`. |
71
- | `--initialDatabase` | `undefined` | Specify the initial database to connect to. This option is only available for the create command and is only relevant for the `postgres` driver, where you always have to connect to a database. If you don't provide a database, the database name will be equal to the connection user name.|
36
+ ### Publish
72
37
 
73
- ### Runtime
38
+ To publish a queue message according the [Message Scheme](#message-types), use the `buildMessage` helper function
39
+ to build a message and the `publishMessage` function to submit it to the message broker.
74
40
 
75
- #### Database
76
- As an alternative to the CLI variant, you can `create` or `drop` the specified/default database through your own code base.
77
- Therefore, you can create the `ConnectionOptions` for the Connection manually, or let it be created automatically:
78
-
79
- **General**
80
41
  ```typescript
81
- import {ConnectionOptions, getConnectionOptions} from 'typeorm';
82
- import {createDatabase, dropDatabase} from "amqp-extension";
83
-
84
- (async () => {
85
- const connectionOptions: ConnectionOptions = await getConnectionOptions();
86
-
87
- // Create database with connection specification
88
- await createDatabase(undefined, connectionOptions);
42
+ import {
43
+ buildMessage,
44
+ Message,
45
+ useConnection,
46
+ publishMessage,
47
+ useConnection
48
+ } from "amqp-extension";
89
49
 
90
- // or without manually specification
91
- await createDatabase({ifNotExist: true});
50
+ // This will set the default connection :)
51
+ useConnection({
52
+ connection: 'amqp://<user>:<password>@<host>',
53
+ exchange: {
54
+ name: '<name>',
55
+ type: 'topic'
56
+ }
57
+ });
92
58
 
59
+ const message: Message = buildMessage({
60
+ type: 'resourceCreated',
61
+ options: {
62
+ routingKey: '<routing-key>'
63
+ }
64
+ });
93
65
 
94
- // Drop Database with connection specification
95
- await dropDatabase(undefined, connectionOptions);
66
+ console.log(message);
67
+ // {id: 'xxxx-xxxx-xxxx-xxxx', type: 'resourceCreated', options: {routingKey: '<routing-key>'}, data: {}, metadata: {}}
96
68
 
97
- // or without manually specification
98
- await dropDatabase({ifExist: true});
69
+ (async () => {
70
+ await publishMessage(message);
99
71
  })();
100
72
  ```
101
73
 
102
- To get a better overview and understanding about the [createDatabase](#createdatabase) and the [dropDatabase](#dropdatabase) function go to the [database functions](#functions---database) section and read more about it.
103
-
104
- #### Query
105
- For explanation proposes of the query utils,
106
- two simple entities with a simple relation between them are declared to demonstrate their usage:
107
-
108
- ```typescript
109
- import {
110
- Entity,
111
- PrimaryGeneratedColumn,
112
- Column,
113
- OneToOne,
114
- JoinColumn
115
- } from "typeorm";
116
-
117
- @Entity()
118
- export class User {
119
- @PrimaryGeneratedColumn({unsigned: true})
120
- id: number;
121
-
122
- @Column({type: 'varchar', length: 30})
123
- @Index({unique: true})
124
- name: string;
125
-
126
- @Column({type: 'varchar', length: 255, default: null, nullable: true})
127
- email: string;
128
-
129
- @OneToOne(() => Profile)
130
- profile: Profile;
131
- }
74
+ ### Consume
132
75
 
133
- @Entity()
134
- export class Profile {
135
- @PrimaryGeneratedColumn({unsigned: true})
136
- id: number;
137
-
138
- @Column({type: 'varchar', length: 255, default: null, nullable: true})
139
- avatar: string;
140
-
141
- @Column({type: 'varchar', length: 255, default: null, nullable: true})
142
- cover: string;
143
-
144
- @OneToOne(() => User)
145
- @JoinColumn()
146
- user: User;
147
- }
148
- ```
149
-
150
- When you use express or another library, you can use the API utils accordingly to the
151
- following code snippet:
76
+ To consume a queue message use the `consumeMessage` function. As first argument it accepts a configuration object
77
+ and as second argument and object to specify an async callback function handler for a specific message `type`.
152
78
 
153
79
  ```typescript
154
- import {getRepository} from "typeorm";
155
- import {Request, Response} from 'express';
156
80
  import {
157
- applyFields,
158
- applyFilters,
159
- applyIncludes,
160
- applyPagination,
161
- applySort
81
+ buildMessage,
82
+ ConsumeOptions,
83
+ Message,
84
+ MessageContext,
85
+ useConnection,
86
+ publishMessage
162
87
  } from "amqp-extension";
163
88
 
164
- /**
165
- * Get many users.
166
- *
167
- * Request example
168
- * - url: /users?page[limit]=10&page[offset]=0&include=profile&filter[id]=1&fields[user]=id,name
169
- *
170
- * Return Example:
171
- * {
172
- * data: [
173
- * {id: 1, name: 'tada5hi', profile: {avatar: 'avatar.jpg', cover: 'cover.jpg'}}
174
- * ],
175
- * meta: {
176
- * total: 1,
177
- * limit: 20,
178
- * offset: 0
179
- * }
180
- * }
181
- * @param req
182
- * @param res
183
- */
184
- export async function getUsers(req: Request, res: Response) {
185
- const {fields, filter, include, page, sort} = req.query;
186
-
187
- const repository = getRepository(User);
188
- const query = repository.createQueryBuilder('user');
189
-
190
- // -----------------------------------------------------
191
-
192
- const includes = applyIncludes(query, include, {
193
- queryAlias: 'user',
194
- allowed: ['profile']
195
- });
196
-
197
- applySort(query, sort, {
198
- queryAlias: 'user',
199
- allowed: ['id', 'name', 'profile.id'],
200
- // profile.id can only be used as sorting key, if the relation 'profile' is included.
201
- includes: includes
202
- });
203
-
204
- applyFields(query, fields, {
205
- queryAlias: 'user',
206
- allowed: ['id', 'name', 'profile.id', 'profile.avatar'],
207
- // porfile fields can only be included, if the relation 'profile' is included.
208
- includes: includes
209
- })
210
-
211
- // only allow filtering users by id & name
212
- applyFilters(query, filter, {
213
- queryAlias: 'user',
214
- allowed: ['id', 'name', 'profile.id'],
215
- // porfile.id can only be used as a filter, if the relation 'profile' is included.
216
- includes: includes
217
- });
218
-
219
- // only allow to select 20 items at maximum.
220
- const pagination = applyPagination(query, page, {maxLimit: 20});
221
-
222
- // -----------------------------------------------------
89
+ // This will set the default connection :)
90
+ useConnection({
91
+ connection: 'amqp://<user>:<password>@<host>',
92
+ exchange: {
93
+ name: '<name>',
94
+ type: 'topic'
95
+ }
96
+ });
223
97
 
224
- const [entities, total] = await query.getManyAndCount();
98
+ const options: ConsumeOptions = {
99
+ routingKey: '<routing-key>'
100
+ }
225
101
 
226
- return res.json({
227
- data: {
228
- data: entities,
229
- meta: {
230
- total,
231
- ...pagination
232
- }
102
+ (async () => {
103
+ await consumeQueue(options, {
104
+ resourceCreated: async (message: Message, messageContext: MessageContext) => {
105
+ // do some async operation :)
106
+ console.log(message);
107
+ // {id: 'xxxx-xxxx-xxxx-xxxx', type: 'resourceCreated', data: {}, metadata: {}}
233
108
  }
234
109
  });
235
- }
110
+ })();
236
111
  ```
237
- To get a better overview and understanding about the [applyFields](#applyfields), [applyFilters](#applyfilters), [applyIncludes](#applyincludes), [applyPagination](#applypagination)
238
- and [applySort](#applysort) function go to the [query functions](#functions---query) section and read more about it.
239
-
240
112
 
241
- ## Functions - Database
113
+ ### Multiple Connections
242
114
 
243
- ### createDatabase
115
+ To define multiple concurrent connections just specify a different `alias` in the configuration object, so it does not
116
+ get overwritten.
244
117
 
245
- ▸ `function` **createDatabase**(`options?: CustomOptions`, `connectionOptions?: ConnectionOptions`): `Promise`<`unknown`>
246
-
247
- Create database.
248
-
249
- #### Example
250
-
251
- **`Status`**
252
118
  ```typescript
253
- // Only create database if it does not exists.
254
- await createDatabase({ifNotExist: true});
255
- ```
256
-
257
- **`Charset`**
258
-
259
- You can also specify the `charset` and `characterSet` as property of the `CustomOptions` parameter
260
- or parse it as extra parameter (ENV: TYPEORM_DRIVER_EXTRA) of the ormconfig.
261
- F.e
262
- - postgres
263
- ```typescript
264
- await createDatabase({ifNotExist: true, characterSet: "UTF8"});
265
- ```
266
- - mysql
267
- ```typescript
268
- await createDatabase({ifNotExist: true, charset: "utf8mb4_general_ci", characterSet: "utf8mb4"});
269
- ```
119
+ import {
120
+ buildMessage,
121
+ ConsumeOptions,
122
+ Message,
123
+ MessageContext,
124
+ useConnection,
125
+ publishMessage
126
+ } from "amqp-extension";
127
+ import {PublishOptions} from "./type";
128
+
129
+ // This will set the default connection :)
130
+ useConnection({
131
+ connection: 'amqp://<user>:<password>@<host>',
132
+ exchange: {
133
+ name: '<name>',
134
+ type: 'topic'
135
+ }
136
+ });
270
137
 
271
- **`ConnectionOptions`**
138
+ useConnection({
139
+ alias: 'foo',
140
+ connection: 'amqp://<user>:<password>@<host>',
141
+ exchange: {
142
+ name: '<name>',
143
+ type: 'topic'
144
+ }
145
+ });
272
146
 
273
- If you have defined `entites` or `subscribers` by environment variables or with another typeorm configuration option,
274
- you may want to use them with ts-node as well with the build (`dist`) variant.
275
- Therefore, you can build the ConnectionOptions with the build in function `buildConnectionOptions`.
147
+ const consumeOptions: ConsumeOptions = {
148
+ routingKey: '<routing-key>',
149
+ alias: 'foo' // <--- use another connection :)
150
+ }
276
151
 
277
- ```typescript
278
- import {craeteDatabase, dropDatabase, buildConnectionOptions} from "amqp-extension";
152
+ const publishOptions: PublishOptions = {
153
+ alias: 'foo' // <--- use another connection :)
154
+ }
279
155
 
280
156
  (async () => {
281
- const connectionOptions = await buildConnectionOptions();
282
- // Create database
283
- await createDatabase({ifNotExist: true}, connectionOptions);
157
+ await consumeQueue({/* handlers */}, consumeOptions);
158
+ await publishMessage({/* message */}, publishOptions);
284
159
  })();
285
- ```
286
- If you have specified the path pattern for the entities like:
287
- `src/database/entities.ts`, the function will rewrite it to `dist/database/entities.js`,
288
- in case the function is not called within the ts-node runtime environment.
289
-
290
- The same logic applies to `seeds` and `factories` path(s) of the `typeorm-seeding` library.
291
160
 
292
- #### Parameters
293
-
294
- | Name | Type | Description |
295
- | :------ | :------ | :------ |
296
- | `options` | `CustomOptions` | Specify custom options like charset, coalition & conditions. |
297
- | `connectionOptions` | `ConnectionOptions` | Pass typeorm connection options object. |
298
-
299
- #### Returns
300
-
301
- `Promise`<`unknown`>
302
-
303
- The function returns a promise with query results provided by underlying db driver.
304
-
305
- ### dropDatabase
306
-
307
- ▸ `function` **dropDatabase**(`options?: CustomOptions`, `connectionOptions?: ConnectionOptions`): `Promise`<`unknown`>
308
-
309
- Drop database.
310
-
311
- #### Example
312
- **`Simple`**
313
- ```typescript
314
- // Only drop database if it does exists.
315
- await dropDatabase({ifExist: true});
316
161
  ```
317
162
 
318
- #### Parameters
163
+ ## Functions
319
164
 
320
- | Name | Type | Description |
321
- | :------ | :------ | :------ |
322
- | `options` | `CustomOptions` | Specify custom options like charset, coalition & conditions. |
323
- | `connectionOptions` | `ConnectionOptions` | Pass typeorm connection options object. |
324
-
325
- #### Returns
326
-
327
- `Promise`<`unknown`>
328
-
329
- The function returns a promise with query results provided by underlying db driver.
165
+ ### useConnection
330
166
 
331
- ## Functions - Query
332
-
333
- ### applyFields
334
-
335
- ▸ `function` **applyFields**<`T`>(`query: SelectQueryBuilder<T>`, `data: unknown`, `options?: FieldsOptions`): `FieldsTransformed`
336
-
337
- Transform fields of the main entity and optional of included relations passed in as `Record<string, string[]>` or `string[]` and apply them to the `SelectQueryBuilder`, in case they match the allowed fields.
167
+ ▸ `function` **useConnection**(`key?: string | Config`): `Promise<Connection>`
338
168
 
169
+ Either register a connection as `default` alias or specify an `alias` as config property.
170
+ If you have registered a connection you can receive the connection by specifying no arguments or provide an alias name if specified.
339
171
  #### Example
340
172
  **`Simple`**
341
173
 
342
174
  ```typescript
343
- // Only drop database if it does exists.
344
- import {applyFields} from "amqp-extension";
345
-
346
- const fields = applyFields(query, ['name'], {
347
- allowed: ['id', 'name'],
348
- queryAlias: 'user'
349
- });
175
+ import {useConnection} from "amqp-extension";
350
176
 
351
- console.log(fields);
352
- // [{alias: 'user', fields: ['name']}]
353
- ```
354
-
355
- #### Type parameters
356
-
357
- | Name | Description |
358
- | :------ | :------ |
359
- | `T` | Typeorm entity type
360
-
361
-
362
- #### Parameters
363
-
364
- | Name | Type | Description |
365
- | :------ | :------ | :------ |
366
- | `query` | `SelectQueryBuilder`<`T`> | Typeorm SelectQueryBuilder Class. |
367
- | `data` | `unknown` | Fields in raw format. F.e `['name']` or `{user: ['name']}`. |
368
- | `options` | `FieldsOptions` | Options for the fields to select.
369
-
370
- #### Returns
371
-
372
- `FieldsTransformed`
373
-
374
- The function returns an array of objects. Each object has the properties `fields` and optional `alias` and `addFields`.
375
-
376
- ### applyFilters
377
-
378
- ▸ `function` **applyFilters**<`T`>(`query: SelectQueryBuilder<T>`, `data: unknown`, `options?: FiltersOptions`): `FiltersTransformed`
379
-
380
- Transform filters of the main entity and optional of included relations passed in as `Record<string, unknown>` and apply them to the `SelectQueryBuilder`, in case they match the allowed filters.
381
-
382
- #### Example
383
- **`Simple`**
384
-
385
- ```typescript
386
- // Only drop database if it does exists.
387
- import {applyFilters} from "amqp-extension";
177
+ (async () => {
388
178
 
389
- const filters = applyFilters(query, {id: 1}, {
390
- allowed: ['id', 'name'],
391
- queryAlias: 'user'
179
+ })();
180
+ const connection = useConnection({
181
+ alias: '<alias>',
182
+ connection: 'amqp://<user>:<password>@<host>',
183
+ exchange: {
184
+ name: '<name>',
185
+ type: 'topic'
186
+ }
392
187
  });
393
-
394
- console.log(filters);
395
- // [{statement: 'user.id = :filter_id', binding: {'filter_id': 1}}]
396
188
  ```
397
189
 
398
190
  #### Type parameters
399
191
 
400
192
  | Name | Description |
401
193
  | :------ | :------ |
402
- | `T` | Typeorm entity type
403
-
404
-
405
- #### Parameters
406
-
407
- | Name | Type | Description |
408
- | :------ | :------ | :------ |
409
- | `query` | `SelectQueryBuilder`<`T`> | Typeorm SelectQueryBuilder Class. |
410
- | `data` | `unknown` | Fields in raw format. F.e `{id: 1}`. |
411
- | `options` | `FiltersOptions` | Options for the fields to select.
412
-
413
- #### Returns
414
-
415
- `FiltersTransformed`
416
-
417
- The function returns an array of objects. Each object has the properties `statement` and `binding`.
418
-
419
-
420
- ### applyIncludes
421
-
422
- ▸ `function` **applyIncludes**<`T`>(`query: SelectQueryBuilder<T>`, `data: unknown`, `options?: IncludesOptions`): `IncludesTransformed`
423
-
424
- Transform relations passed in as `string`, `string[]` and apply them to the `SelectQueryBuilder`, in case they match the allowed relations.
425
-
426
- #### Example
427
- **`Simple`**
428
-
429
- ```typescript
430
- // Only drop database if it does exists.
431
- import {applyIncludes} from "amqp-extension";
432
194
 
433
- const includes = applyIncludes(query, ['roles'], {
434
- allowed: ['roles', 'photos'],
435
- queryAlias: 'user'
436
- });
437
-
438
- console.log(includes);
439
- // [{property: 'user.roles', alias: 'roles'}]
440
- ```
441
-
442
- #### Type parameters
443
-
444
- | Name | Description |
445
- | :------ | :------ |
446
- | `T` | Typeorm entity type
447
195
 
448
196
 
449
197
  #### Parameters
450
198
 
451
199
  | Name | Type | Description |
452
200
  | :------ | :------ | :------ |
453
- | `query` | `SelectQueryBuilder`<`T`> | Typeorm SelectQueryBuilder Class. |
454
- | `data` | `unknown` | Relations in raw format. F.e `['roles']` or `roles` |
455
- | `options` | `IncludesOptions` | Options for the relations to include.
201
+ | `key` | `string` or `Config` | Config or alias of config. [more](#config-types) |
456
202
 
457
203
  #### Returns
458
204
 
459
- `IncludesTransformed`
205
+ `Promise<Connection>`
460
206
 
461
- The function returns an array of objects. Each object has the properties `property` and `alias`.
207
+ The function returns the Connection object of the `amqplib`.
462
208
 
463
- ### applyPagination
209
+ ### publishMessage
464
210
 
465
- ▸ `function` **applyPagination**<`T`>(`query: SelectQueryBuilder<T>`, `data: unknown`, `options?: PaginationOptions`): `PaginationTransformed`
466
-
467
- Transform pagination data passed in as `{limit?: number, offset?: number}` and apply it to the `SelectQueryBuilder`.
211
+ ▸ `function` **publishMessage**(`message: Message`, `options?: PublishOptions`): `Promise<void>`
468
212
 
213
+ Send the constructed queue message to the message broker.
214
+ As second parameter a registered config can be used by specifying the alias or provide the full config object.
469
215
  #### Example
470
216
  **`Simple`**
471
217
 
472
218
  ```typescript
473
- // Only drop database if it does exists.
474
- import {applyPagination} from "amqp-extension";
219
+ import {
220
+ buildMessage,
221
+ publishMessage
222
+ } from "amqp-extension";
475
223
 
476
- const pagination = applyPagination(query, {limit: 100}, {
477
- maxLimit: 50
224
+ const message: Message = buildMessage({
225
+ type: 'resourceCreated',
226
+ options: {
227
+ routingKey: '<routing-key>'
228
+ }
478
229
  });
479
230
 
480
- console.log(pagination);
481
- // {limit: 50}
231
+ console.log(message);
232
+ // {id: 'xxxx-xxxx-xxxx-xxxx', type: 'resourceCreated', options: {routingKey: '<routing-key>'}, data: {}, metadata: {}}
233
+
234
+ (async () => {
235
+ await publishMessage(message);
236
+ })();
482
237
  ```
483
238
 
484
239
  #### Type parameters
485
240
 
486
241
  | Name | Description |
487
242
  | :------ | :------ |
488
- | `T` | Typeorm entity type
489
-
490
243
 
491
244
  #### Parameters
492
245
 
493
246
  | Name | Type | Description |
494
247
  | :------ | :------ | :------ |
495
- | `query` | `SelectQueryBuilder`<`T`> | Typeorm SelectQueryBuilder Class. |
496
- | `data` | `unknown` | Pagination data in raw format. F.e `{limit: 20, offset: 10}`. |
497
- | `options` | `PaginationOptions` | Options for the pagination to select.
248
+ | `message` | `Message` | Constructed message object. [more](#message-types)|
249
+ | `options` | `PublishOptions` | Publish options. [more](#publish-types) |
498
250
 
499
251
  #### Returns
500
252
 
501
- `PaginationTransformed`
502
-
503
- The function returns an object. The object might have the properties `limit` and `offset`.
253
+ `Promise<void>`
504
254
 
505
- ### applySort
255
+ The function does not return a value.
506
256
 
507
- ▸ `function` **applySort**<`T`>(`query: SelectQueryBuilder<T>`, `data: unknown`, `options?: SortOptions`): `SortTransformed`
257
+ ### consumeQueue
508
258
 
509
- Transform sort fields passed in as `string`, `string[]` and apply them to the `SelectQueryBuilder`, in case they match the allowed fields to sort.
259
+ ▸ `function` **consumeQueue**(`options: ConsumeOptions`, `cb: ConsumeHandlers`): `Promise<void>`
510
260
 
261
+ Send the constructed queue message to the message broker.
262
+ As second parameter a registered config can be used by specifying the alias or provide the full config object.
511
263
  #### Example
512
264
  **`Simple`**
513
265
 
514
266
  ```typescript
515
- // Only drop database if it does exists.
516
- import {applySort} from "amqp-extension";
267
+ import {
268
+ consumeQueue,
269
+ ConsumeOptions,
270
+ Message,
271
+ MessageContext
272
+ } from "amqp-extension";
517
273
 
518
- const sort = applySort(query, ['-name'], {
519
- allowed: ['id', 'name'],
520
- queryAlias: 'user'
521
- });
274
+ const options: ConsumeOptions = {
275
+ routingKey: '<routing-key>'
276
+ }
277
+
278
+ (async () => {
279
+ await consumeQueue(options, {
280
+ '<type>': async (message: Message, messageContext: MessageContext) => {
281
+ // do some async action :)
282
+ console.log(message);
283
+ // {id: 'xxxx-xxxx-xxxx-xxxx', type: 'resourceCreated', data: {}, metadata: {}}
284
+ }
285
+ });
286
+ })();
522
287
 
523
- console.log(sort);
524
- // {'user.name': 'DESC'}
525
288
  ```
526
289
 
527
290
  #### Type parameters
528
291
 
529
292
  | Name | Description |
530
293
  | :------ | :------ |
531
- | `T` | Typeorm entity type
294
+
532
295
 
533
296
 
534
297
  #### Parameters
535
298
 
536
299
  | Name | Type | Description |
537
300
  | :------ | :------ | :------ |
538
- | `query` | `SelectQueryBuilder`<`T`> | Typeorm SelectQueryBuilder Class. |
539
- | `data` | `unknown` | Sorting Fields in raw format. F.e `['-name']`, `-name` or `{name: 'DESC'}`. The hyphen prefix indicates descending order. |
540
- | `options` | `SortOptions` | Options for the sorting strategy.
301
+ | `options` | `ConsumeOptions` | Consume options. [more](#consume-types)|
302
+ | `handlers` | `ConsumeHandlers` | Handlers object. [more](#consume-types) |
541
303
 
542
304
  #### Returns
543
305
 
544
- `SortTransformed`
306
+ `Promise<void>`
545
307
 
546
- The function returns an objects. Each key-value pair represents a field and the corresponding sorting direction.
308
+ The function does not return a value.
547
309
 
548
310
  ## Types
549
311
 
550
- ### Types - Database
312
+ ### Config Types
551
313
 
552
- #### CustomOptions
553
314
  ```typescript
554
- type CustomOptions = {
555
- characterSet?: string,
556
- charset?: string,
557
- ifExist?: boolean,
558
- ifNotExist?: boolean,
559
- initialDatabase?: string
315
+ import {Options} from "amqplib";
316
+ import {PublishOptions} from "amqp-extension";
317
+
318
+ export type ExchangeType = 'fanout' | 'direct' | 'topic' | 'match' | string;
319
+
320
+ export type Config = {
321
+ alias?: string,
322
+ connection: Options.Connect | string,
323
+ exchange: {
324
+ name: string,
325
+ type: ExchangeType,
326
+ options?: Options.AssertExchange
327
+ },
328
+ publish?: PublishOptions,
329
+ consume?: ConsumeOptions
560
330
  };
561
331
  ```
562
332
 
563
- ### Types - Query
564
-
565
- #### FieldsOptions
333
+ ### Consume Types
566
334
  ```typescript
567
- type FieldsOptions = {
568
- aliasMapping?: Record<string, string>,
569
- allowed?: Record<string, string[]> | string[],
570
- includes?: IncludesTransformed,
571
- queryAlias?: string
572
- };
335
+ import {Options} from "amqplib";
336
+ import {Config, MessageContext, Message} from "amqp-extension";
337
+
338
+ export type ConsumeHandler = (message: Message, context: MessageContext) => Promise<void>;
339
+ export type ConsumeHandlers = Record<'$any' | string, ConsumeHandler>;
340
+
341
+ export type ConsumeOptions = {
342
+ /**
343
+ * Queue routing key(s).
344
+ */
345
+ routingKey?: string | string[],
346
+
347
+ /**
348
+ * Config key or object.
349
+ */
350
+ alias?: string | Config,
351
+ /**
352
+ * Queue name.
353
+ *
354
+ * Default: ''
355
+ */
356
+ name?: string,
357
+ /**
358
+ * Amqplib consume options.
359
+ *
360
+ * Default: {}
361
+ */
362
+ options?: Options.Consume
363
+ }
573
364
  ```
574
365
 
575
- #### FiltersOptions
576
- ```typescript
577
- export type FiltersOptions = {
578
- aliasMapping?: Record<string, string>,
579
- allowed?: string[],
580
- includes?: IncludesTransformed,
581
- queryAlias?: string,
582
- queryBindingKeyFn?: (key: string) => string
583
- };
584
- ```
366
+ ### Message Types
585
367
 
586
- #### IncludesOptions
587
368
  ```typescript
588
- type IncludesOptions = {
589
- aliasMapping?: Record<string, string>,
590
- allowed?: string[],
591
- includeParents?: boolean | string[] | string
592
- queryAlias?: string,
593
- };
594
- ```
369
+ import {Options} from "amqplib";
370
+
371
+ export interface MessageOptions {
372
+ /**
373
+ * Routing key for message broker.
374
+ */
375
+ routingKey?: string;
376
+ /**
377
+ * Override default publish options.
378
+ */
379
+ publish?: Options.Publish;
380
+ }
595
381
 
596
- #### PaginationOptions
597
- ```typescript
598
- type PaginationOptions = {
599
- maxLimit?: number
382
+ export type Message = {
383
+ /**
384
+ * Routing information for amqp library.
385
+ * This property will be removed, before it is passed to the message queue.
386
+ */
387
+ options?: MessageOptions;
388
+
389
+ /**
390
+ *
391
+ * Default: <generated uuid>
392
+ */
393
+ id: string;
394
+
395
+ /**
396
+ * Event- or Command-name.
397
+ */
398
+ type: string;
399
+
400
+ /**
401
+ * Metadata object to provide details for the message broker.
402
+ *
403
+ * Default: {}
404
+ */
405
+ metadata: Record<string, any>;
406
+
407
+ /**
408
+ * The message data.
409
+ *
410
+ * Default: {}
411
+ */
412
+ data: Record<string, any>;
600
413
  };
601
414
  ```
602
415
 
603
- #### SortOptions
416
+ ### Publish Types
417
+
604
418
  ```typescript
605
- type SortOptions = {
606
- aliasMapping?: Record<string, string>,
607
- allowed?: string[] | string[][],
608
- includes?: IncludesTransformed,
609
- queryAlias?: string
610
- };
419
+ import {Options} from "amqplib";
420
+ import {Config} from "amqp-extension";
421
+
422
+ export type PublishOptions = {
423
+ /**
424
+ * Config key or object.
425
+ */
426
+ alias?: string | Config;
427
+
428
+ /**
429
+ * Amqplib publish options.
430
+ */
431
+ options?: Options.Publish;
432
+ }
433
+
611
434
  ```