core-services-sdk 1.3.7 → 1.3.9

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 (36) hide show
  1. package/package.json +6 -5
  2. package/src/fastify/error-codes.js +11 -0
  3. package/src/http/HttpError.js +84 -10
  4. package/src/http/http.js +41 -31
  5. package/src/http/index.js +4 -0
  6. package/src/http/responseType.js +10 -0
  7. package/src/ids/index.js +2 -0
  8. package/src/index.js +7 -21
  9. package/src/mailer/transport.factory.js +28 -14
  10. package/src/mongodb/initialize-mongodb.js +9 -7
  11. package/src/rabbit-mq/index.js +1 -186
  12. package/src/rabbit-mq/rabbit-mq.js +189 -0
  13. package/src/templates/index.js +1 -0
  14. package/tests/fastify/error-handler.unit.test.js +39 -0
  15. package/tests/{with-error-handling.test.js → fastify/error-handlers/with-error-handling.test.js} +4 -3
  16. package/tests/http/HttpError.unit.test.js +112 -0
  17. package/tests/http/http-method.unit.test.js +29 -0
  18. package/tests/http/http.unit.test.js +167 -0
  19. package/tests/http/responseType.unit.test.js +45 -0
  20. package/tests/ids/prefixes.unit.test.js +1 -0
  21. package/tests/mailer/mailer.integration.test.js +95 -0
  22. package/tests/{mailer.unit.test.js → mailer/mailer.unit.test.js} +7 -11
  23. package/tests/mailer/transport.factory.unit.test.js +204 -0
  24. package/tests/mongodb/connect.unit.test.js +60 -0
  25. package/tests/mongodb/initialize-mongodb.unit.test.js +98 -0
  26. package/tests/mongodb/validate-mongo-uri.unit.test.js +52 -0
  27. package/tests/{rabbit-mq.test.js → rabbit-mq/rabbit-mq.test.js} +3 -2
  28. package/tests/{template-loader.integration.test.js → templates/template-loader.integration.test.js} +1 -1
  29. package/tests/{template-loader.unit.test.js → templates/template-loader.unit.test.js} +1 -1
  30. package/vitest.config.js +3 -0
  31. package/index.js +0 -3
  32. package/tests/HttpError.test.js +0 -80
  33. package/tests/core-util.js +0 -24
  34. package/tests/mailer.integration.test.js +0 -46
  35. package/tests/mongodb.test.js +0 -70
  36. package/tests/transport.factory.unit.test.js +0 -128
@@ -0,0 +1,98 @@
1
+ // @ts-nocheck
2
+ import { describe, it, expect, vi, beforeEach } from 'vitest'
3
+
4
+ import { initializeMongoDb } from '../../src/mongodb/initialize-mongodb.js'
5
+
6
+ // Shared session spy
7
+ const sessionSpy = {
8
+ startTransaction: vi.fn(),
9
+ commitTransaction: vi.fn(),
10
+ abortTransaction: vi.fn(),
11
+ endSession: vi.fn(),
12
+ }
13
+
14
+ // ✅ Mock path must match actual import in initializeMongoDb
15
+ vi.mock('../../src/mongodb/connect.js', () => {
16
+ const fakeCollection = (name) => ({
17
+ name,
18
+ insertOne: vi.fn(),
19
+ })
20
+
21
+ const fakeDb = {
22
+ collection: vi.fn((name) => fakeCollection(name)),
23
+ }
24
+
25
+ const fakeClient = {
26
+ db: vi.fn(() => fakeDb),
27
+ startSession: () => sessionSpy,
28
+ close: vi.fn(),
29
+ }
30
+
31
+ return {
32
+ mongoConnect: vi.fn(async () => fakeClient),
33
+ }
34
+ })
35
+
36
+ import { mongoConnect } from '../../src/mongodb/connect.js'
37
+
38
+ describe('initializeMongoDb', () => {
39
+ const config = {
40
+ uri: 'mongodb://localhost:27017',
41
+ options: { dbName: 'testdb' },
42
+ }
43
+
44
+ const collectionNames = {
45
+ users: 'users_collection',
46
+ logs: 'logs_collection',
47
+ }
48
+
49
+ beforeEach(() => {
50
+ vi.clearAllMocks()
51
+ })
52
+
53
+ it('should initialize collections correctly', async () => {
54
+ const db = await initializeMongoDb({ config, collectionNames })
55
+
56
+ expect(mongoConnect).toHaveBeenCalledWith(config)
57
+ expect(db.users.name).toBe('users_collection')
58
+ expect(db.logs.name).toBe('logs_collection')
59
+ })
60
+
61
+ it('should expose the mongo client via getter', async () => {
62
+ const db = await initializeMongoDb({ config, collectionNames })
63
+ expect(db.client).toBeDefined()
64
+ expect(db.client.db).toBeTypeOf('function')
65
+ })
66
+
67
+ it('should run actions within a transaction and commit on success', async () => {
68
+ const db = await initializeMongoDb({ config, collectionNames })
69
+
70
+ const actionMock = vi.fn(async ({ session }) => {
71
+ expect(session).toBe(sessionSpy)
72
+ })
73
+
74
+ await db.withTransaction(actionMock)
75
+
76
+ expect(sessionSpy.startTransaction).toHaveBeenCalled()
77
+ expect(sessionSpy.commitTransaction).toHaveBeenCalled()
78
+ expect(sessionSpy.abortTransaction).not.toHaveBeenCalled()
79
+ expect(sessionSpy.endSession).toHaveBeenCalled()
80
+ })
81
+
82
+ it('should abort transaction on error', async () => {
83
+ const db = await initializeMongoDb({ config, collectionNames })
84
+
85
+ const actionMock = vi.fn(async () => {
86
+ throw new Error('Intentional failure')
87
+ })
88
+
89
+ await expect(db.withTransaction(actionMock)).rejects.toThrow(
90
+ 'Intentional failure',
91
+ )
92
+
93
+ expect(sessionSpy.startTransaction).toHaveBeenCalled()
94
+ expect(sessionSpy.commitTransaction).not.toHaveBeenCalled()
95
+ expect(sessionSpy.abortTransaction).toHaveBeenCalled()
96
+ expect(sessionSpy.endSession).toHaveBeenCalled()
97
+ })
98
+ })
@@ -0,0 +1,52 @@
1
+ // @ts-nocheck
2
+ import { describe, it, expect } from 'vitest'
3
+
4
+ import { isValidMongoUri } from '../../src/mongodb/validate-mongo-uri.js'
5
+
6
+ describe('isValidMongoUri', () => {
7
+ it('should return true for a valid mongodb:// URI', () => {
8
+ expect(isValidMongoUri('mongodb://localhost:27017/mydb')).toBe(true)
9
+ })
10
+
11
+ it('should return true for a valid mongodb+srv:// URI', () => {
12
+ expect(isValidMongoUri('mongodb+srv://cluster.example.com/test')).toBe(true)
13
+ })
14
+
15
+ it('should return false for non-MongoDB protocol (http)', () => {
16
+ expect(isValidMongoUri('http://localhost')).toBe(false)
17
+ })
18
+
19
+ it('should return false for empty string', () => {
20
+ expect(isValidMongoUri('')).toBe(false)
21
+ })
22
+
23
+ it('should return false for whitespace string', () => {
24
+ expect(isValidMongoUri(' ')).toBe(false)
25
+ })
26
+
27
+ it('should return false for non-string input', () => {
28
+ expect(isValidMongoUri(null)).toBe(false)
29
+ expect(isValidMongoUri(undefined)).toBe(false)
30
+ expect(isValidMongoUri(12345)).toBe(false)
31
+ expect(isValidMongoUri({})).toBe(false)
32
+ })
33
+
34
+ it('should return false for malformed URI', () => {
35
+ expect(isValidMongoUri('mongodb://')).toBe(false)
36
+ expect(isValidMongoUri('mongodb+srv://')).toBe(false)
37
+ expect(isValidMongoUri('mongodb:/localhost')).toBe(false)
38
+ })
39
+
40
+ it('should allow valid URIs with credentials and options', () => {
41
+ expect(
42
+ isValidMongoUri(
43
+ 'mongodb://user:pass@localhost:27017/mydb?retryWrites=true',
44
+ ),
45
+ ).toBe(true)
46
+ expect(
47
+ isValidMongoUri(
48
+ 'mongodb+srv://user:pass@cluster0.example.mongodb.net/mydb',
49
+ ),
50
+ ).toBe(true)
51
+ })
52
+ })
@@ -1,5 +1,6 @@
1
1
  import { describe, it, expect, beforeAll } from 'vitest'
2
- import { initializeQueue, rabbitUriFromEnv } from '../src/rabbit-mq/index.js'
2
+
3
+ import { initializeQueue, rabbitUriFromEnv } from '../../src/rabbit-mq/index.js'
3
4
 
4
5
  const sleep = (ms) => new Promise((res) => setTimeout(res, ms))
5
6
 
@@ -37,8 +38,8 @@ describe('RabbitMQ SDK', () => {
37
38
  describe('rabbitUriFromEnv', () => {
38
39
  it('should build valid amqp URI from env', () => {
39
40
  const env = {
40
- RABBIT_HOST: '0.0.0.0',
41
41
  RABBIT_PORT: 5672,
42
+ RABBIT_HOST: '0.0.0.0',
42
43
  RABBIT_USERNAME: 'botq',
43
44
  RABBIT_PASSWORD: 'botq',
44
45
  _RABBIT_HOST: '0.0.0.0',
@@ -3,7 +3,7 @@ import { tmpdir } from 'os'
3
3
  import { writeFile, rm, mkdir } from 'fs/promises'
4
4
  import { describe, it, expect, beforeAll, afterAll } from 'vitest'
5
5
 
6
- import { loadTemplates } from '../src/templates/template-loader.js'
6
+ import { loadTemplates } from '../../src/templates/template-loader.js'
7
7
 
8
8
  const tempDir = join(tmpdir(), 'template-tests')
9
9
 
@@ -2,7 +2,7 @@ import dot from 'dot'
2
2
  import * as fs from 'fs/promises'
3
3
  import { describe, it, expect, vi, beforeEach } from 'vitest'
4
4
 
5
- import { loadTemplates } from '../src/templates/template-loader.js'
5
+ import { loadTemplates } from '../../src/templates/template-loader.js'
6
6
 
7
7
  vi.mock('fs/promises')
8
8
 
package/vitest.config.js CHANGED
@@ -2,5 +2,8 @@ export default {
2
2
  test: {
3
3
  testTimeout: 30000,
4
4
  hookTimeout: 30000,
5
+ coverage: {
6
+ exclude: ['**/index.js', 'vitest.config.js'],
7
+ },
5
8
  },
6
9
  }
package/index.js DELETED
@@ -1,3 +0,0 @@
1
- import { HttpError } from './src/index.js'
2
-
3
- throw new HttpError({ code: '2', httpStatusCode: 22 })
@@ -1,80 +0,0 @@
1
- import { describe, it, expect } from 'vitest'
2
- import { HttpError } from '../src/http/HttpError.js'
3
- import httpStatus from 'http-status'
4
-
5
- describe('HttpError', () => {
6
- it('creates an error with all fields explicitly set', () => {
7
- const err = new HttpError({
8
- code: 'SOME_ERROR',
9
- message: 'Something went wrong',
10
- httpStatusCode: httpStatus.BAD_REQUEST,
11
- httpStatusText: httpStatus[httpStatus.BAD_REQUEST],
12
- })
13
-
14
- expect(err).toBeInstanceOf(HttpError)
15
- expect(err.message).toBe('Something went wrong')
16
- expect(err.code).toBe('SOME_ERROR')
17
- expect(err.httpStatusCode).toBe(httpStatus.BAD_REQUEST)
18
- expect(err.httpStatusText).toBe(httpStatus[httpStatus.BAD_REQUEST])
19
- })
20
-
21
- it('falls back to code if message and httpStatusCode are missing', () => {
22
- const err = new HttpError({ code: 'MY_CODE' })
23
- expect(err.message).toBe('MY_CODE')
24
- expect(err.code).toBe('MY_CODE')
25
- })
26
-
27
- it('falls back to status text if only httpStatusCode is provided', () => {
28
- const err = new HttpError({ httpStatusCode: httpStatus.NOT_FOUND })
29
- expect(err.message).toBe(httpStatus[httpStatus.NOT_FOUND])
30
- expect(err.httpStatusText).toBe(httpStatus[httpStatus.NOT_FOUND])
31
- expect(err.httpStatusCode).toBe(httpStatus.NOT_FOUND)
32
- })
33
-
34
- it('falls back to "Unknown error" if nothing is provided', () => {
35
- const err = new HttpError()
36
- expect(err.message).toBe('Unknown error')
37
- expect(err.code).toBeUndefined()
38
- expect(err.httpStatusCode).toBeUndefined()
39
- expect(err.httpStatusText).toBeUndefined()
40
- })
41
-
42
- it('uses httpStatusText if not explicitly set but httpStatusCode is present', () => {
43
- const err = new HttpError({ httpStatusCode: httpStatus.UNAUTHORIZED })
44
- expect(err.httpStatusText).toBe(httpStatus[httpStatus.UNAUTHORIZED])
45
- })
46
-
47
- it('supports static isInstanceOf check', () => {
48
- const err = new HttpError()
49
- expect(HttpError.isInstanceOf(err)).toBe(true)
50
- expect(HttpError.isInstanceOf(new Error())).toBe(false)
51
- })
52
-
53
- it('supports Symbol.hasInstance (dynamic instanceof)', () => {
54
- const fake = {
55
- code: 'FAKE',
56
- message: 'Fake error',
57
- httpStatusCode: httpStatus.UNAUTHORIZED,
58
- httpStatusText: httpStatus[httpStatus.UNAUTHORIZED],
59
- }
60
-
61
- expect(fake instanceof HttpError).toBe(true)
62
- })
63
-
64
- it('serializes correctly via toJSON', () => {
65
- const err = new HttpError({
66
- code: 'TOO_FAST',
67
- message: 'You are too fast',
68
- httpStatusCode: httpStatus.TOO_MANY_REQUESTS,
69
- httpStatusText: httpStatus[httpStatus.TOO_MANY_REQUESTS],
70
- })
71
-
72
- const json = JSON.stringify(err)
73
- expect(JSON.parse(json)).toEqual({
74
- code: 'TOO_FAST',
75
- message: 'You are too fast',
76
- httpStatusCode: httpStatus.TOO_MANY_REQUESTS,
77
- httpStatusText: httpStatus[httpStatus.TOO_MANY_REQUESTS],
78
- })
79
- })
80
- })
@@ -1,24 +0,0 @@
1
- import { exec } from 'child_process'
2
- /**
3
- * Starts a MongoDB Docker container on the specified port.
4
- * @param {string} command - Command to run, like: 'docker run -d --name mongo-test -p 2730:27017 mongo'.
5
- * @returns {Promise<void>}
6
- */
7
- export const runInTerminal = async (command) => {
8
- return new Promise((resolve, reject) => {
9
- exec(command, (error, stdout, stderr) => {
10
- if (error) {
11
- console.error('Error starting command:', error.message)
12
- return reject(error)
13
- }
14
- if (stderr) {
15
- console.warn('stderr:', stderr)
16
- }
17
- console.log('Command started:', stdout.trim())
18
- resolve()
19
- })
20
- })
21
- }
22
-
23
- export const sleep = async (milliseconds) =>
24
- new Promise((res) => setTimeout(res, milliseconds))
@@ -1,46 +0,0 @@
1
- import { describe, it, expect } from 'vitest'
2
- import nodemailer from 'nodemailer'
3
- import { Mailer } from '../src/mailer/mailer.service.js'
4
-
5
- describe('Mailer (integration)', () => {
6
- it('should send email using ethereal SMTP', async () => {
7
- // Create ethereal test account
8
- const testAccount = await nodemailer.createTestAccount()
9
-
10
- // Create Nodemailer transporter for ethereal
11
- const transporter = nodemailer.createTransport({
12
- host: testAccount.smtp.host,
13
- port: testAccount.smtp.port,
14
- secure: testAccount.smtp.secure,
15
- auth: {
16
- user: testAccount.user,
17
- pass: testAccount.pass,
18
- },
19
- })
20
-
21
- // Create Mailer instance
22
- const mailer = new Mailer(transporter)
23
-
24
- // Send test email
25
- const result = await mailer.send({
26
- to: 'recipient@example.com',
27
- text: 'Hello from test - plain text',
28
- from: '"My App" <no-reply@example.com>',
29
- subject: 'core-service-sdk:Integration Test Email',
30
- html: '<h1>Hello from core-service-sdk test</h1><p>This is a core-service-sdk</p>',
31
- cc: '',
32
- bcc: '',
33
- replyTo: '',
34
- attachments: '',
35
- })
36
-
37
- // Assert response
38
- expect(result.messageId).toBeDefined()
39
-
40
- // Print preview URL (clickable in terminal)
41
- const previewUrl = nodemailer.getTestMessageUrl(result)
42
- console.log(`📨 Preview this email: ${previewUrl}`)
43
-
44
- expect(previewUrl).toMatch(/^https:\/\/ethereal\.email/)
45
- })
46
- })
@@ -1,70 +0,0 @@
1
- import { describe, it, expect, beforeAll, afterAll } from 'vitest'
2
- import { runInTerminal, sleep } from './core-util.js'
3
- import { initializeMongoDb } from '../src/mongodb/index.js'
4
-
5
- const port = 2730
6
- const dbName = 'testdb'
7
- const host = 'localhost'
8
- const mongoUri = `mongodb://${host}:${port}/?replicaSet=rs0`
9
- const dockerStopCommand = `docker stop ${dbName} && docker rm ${dbName}`
10
- const dockerCreateCommant = `docker run -d --name ${dbName} -p ${port}:27017 mongo --replSet rs0`
11
- const dockerReplicaSetCommand = `docker exec -i ${dbName} mongosh --eval "rs.initiate()"`
12
-
13
- describe('MongoDB Init & Transaction SDK', () => {
14
- let collections
15
-
16
- beforeAll(async () => {
17
- try {
18
- await runInTerminal(dockerStopCommand)
19
- } catch (error) {
20
- console.log('No existing container to stop.')
21
- }
22
-
23
- await runInTerminal(dockerCreateCommant)
24
- await sleep(5000)
25
- await runInTerminal(dockerReplicaSetCommand)
26
-
27
- collections = await initializeMongoDb({
28
- config: {
29
- uri: mongoUri,
30
- options: { dbName },
31
- },
32
- collectionNames: {
33
- users: 'users',
34
- logs: 'logs',
35
- },
36
- })
37
-
38
- await collections.users.deleteMany({})
39
- await collections.logs.deleteMany({})
40
- }, 60000)
41
-
42
- afterAll(async () => {
43
- if (collections?.client) {
44
- await collections.client.db(dbName).dropDatabase()
45
- await collections.client.close()
46
- }
47
- }, 20000)
48
-
49
- it.skip('should insert into multiple collections within a transaction', async () => {
50
- if (!collections) throw new Error('collections not initialized')
51
-
52
- await collections.withTransaction(async ({ session }) => {
53
- const userInsert = collections.users.insertOne(
54
- { name: 'Alice' },
55
- { session },
56
- )
57
- const logInsert = collections.logs.insertOne(
58
- { action: 'UserCreated', user: 'Alice' },
59
- { session },
60
- )
61
- await Promise.all([userInsert, logInsert])
62
- })
63
-
64
- const insertedUser = await collections.users.findOne({ name: 'Alice' })
65
- const insertedLog = await collections.logs.findOne({ user: 'Alice' })
66
-
67
- expect(insertedUser).not.toBeNull()
68
- expect(insertedLog).not.toBeNull()
69
- }, 20000)
70
- }, 60000)
@@ -1,128 +0,0 @@
1
- import aws from 'aws-sdk'
2
- import nodemailer from 'nodemailer'
3
- import { describe, it, expect, vi } from 'vitest'
4
- import sgTransport from 'nodemailer-sendgrid-transport'
5
-
6
- vi.mock('nodemailer', () => {
7
- const createTransport = vi.fn((options) => ({
8
- type: 'mock-transport',
9
- options,
10
- }))
11
- return {
12
- __esModule: true,
13
- default: { createTransport },
14
- createTransport,
15
- }
16
- })
17
-
18
- vi.mock('aws-sdk', () => {
19
- return {
20
- __esModule: true,
21
- default: {
22
- SES: vi.fn(() => 'mocked-ses'),
23
- },
24
- }
25
- })
26
-
27
- vi.mock('nodemailer-sendgrid-transport', () => {
28
- return {
29
- __esModule: true,
30
- default: vi.fn((opts) => ({
31
- sendgrid: true,
32
- options: opts,
33
- })),
34
- }
35
- })
36
-
37
- import { TransportFactory } from '../src/mailer/transport.factory.js'
38
- describe('TransportFactory', () => {
39
- it('should create smtp transport', () => {
40
- const config = {
41
- type: 'smtp',
42
- host: 'smtp.example.com',
43
- port: 587,
44
- secure: false,
45
- auth: { user: 'user', pass: 'pass' },
46
- }
47
-
48
- const transport = TransportFactory.create(config)
49
- expect(nodemailer.createTransport).toHaveBeenCalledWith({
50
- host: config.host,
51
- port: config.port,
52
- secure: config.secure,
53
- auth: config.auth,
54
- })
55
- expect(transport.type).toBe('mock-transport')
56
- })
57
-
58
- it('should create gmail transport', () => {
59
- const config = {
60
- type: 'gmail',
61
- auth: { user: 'user@gmail.com', pass: 'pass' },
62
- }
63
-
64
- const transport = TransportFactory.create(config)
65
- expect(nodemailer.createTransport).toHaveBeenCalledWith({
66
- service: 'gmail',
67
- auth: config.auth,
68
- })
69
- expect(transport.type).toBe('mock-transport')
70
- })
71
-
72
- it('should create sendgrid transport', () => {
73
- const config = {
74
- type: 'sendgrid',
75
- apiKey: 'SG.xxxx',
76
- }
77
-
78
- const transport = TransportFactory.create(config)
79
-
80
- expect(nodemailer.createTransport).toHaveBeenCalled()
81
-
82
- const args = nodemailer.createTransport.mock.calls[0][0]
83
-
84
- expect(args).toEqual({
85
- sendgrid: true,
86
- options: {
87
- auth: { api_key: config.apiKey },
88
- },
89
- })
90
-
91
- expect(transport).toEqual({
92
- type: 'mock-transport',
93
- options: {
94
- sendgrid: true,
95
- options: {
96
- auth: { api_key: config.apiKey },
97
- },
98
- },
99
- })
100
- })
101
-
102
- it('should create ses transport', () => {
103
- const config = {
104
- type: 'ses',
105
- accessKeyId: 'AKIA...',
106
- secretAccessKey: 'secret',
107
- region: 'us-west-2',
108
- }
109
-
110
- TransportFactory.create(config)
111
-
112
- expect(nodemailer.createTransport).toHaveBeenCalled()
113
- const args = nodemailer.createTransport.mock.calls[0][0]
114
-
115
- expect(args).toEqual({
116
- SES: {
117
- ses: 'mocked-ses',
118
- aws: expect.anything(),
119
- },
120
- })
121
- })
122
-
123
- it('should throw error for unsupported type', () => {
124
- expect(() => {
125
- TransportFactory.create({ type: 'unsupported' })
126
- }).toThrow('Unsupported transport type: unsupported')
127
- })
128
- })