-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathservice-extending.spec.ts
More file actions
84 lines (67 loc) · 2.14 KB
/
service-extending.spec.ts
File metadata and controls
84 lines (67 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* eslint-disable @typescript-eslint/no-unused-expressions */
import { z } from 'zod';
import chai from 'chai';
import spies from 'chai-spies';
import 'mocha';
import {
Database, eventBus, Service, ServiceOptions,
} from '../index';
import { IDocument } from '../types';
import config from '../config';
chai.use(spies);
chai.should();
const database = new Database(config.mongo.connection, config.mongo.dbName);
class CustomService<T extends IDocument> extends Service<T> {
createOrUpdate = async (query: any, updateCallback: (item?: T) => Partial<T>) => {
const docExists = await this.exists(query);
if (!docExists) {
const newDoc = updateCallback();
return this.insertOne(newDoc);
}
return this.updateOne(query, (doc) => updateCallback(doc));
};
}
function createService<T extends IDocument>(collectionName: string, options: ServiceOptions<T> = {}) {
return new CustomService<T>(collectionName, database, options);
}
const schema = z.object({
_id: z.string(),
createdOn: z.date().optional(),
updatedOn: z.date().optional(),
deletedOn: z.date().optional().nullable(),
fullName: z.string(),
});
type UserType = z.infer<typeof schema>;
const usersService = createService<UserType>('users', {
schemaValidator: (obj) => schema.parseAsync(obj),
});
describe('extending service.ts', () => {
before(async () => {
await database.connect();
});
after(async () => {
await usersService.drop();
await database.close();
});
it('should create document and publish users.created event', async () => {
const spy = chai.spy();
eventBus.on('users.created', spy);
await usersService.createOrUpdate(
{ _id: 'some-id' },
() => ({ fullName: 'Max' }),
);
spy.should.have.been.called.at.least(1);
});
it('should update document and publish users.updated event', async () => {
const user = await usersService.insertOne({
fullName: 'Max',
});
const spy = chai.spy();
eventBus.on('users.updated', spy);
await usersService.createOrUpdate(
{ _id: user._id },
() => ({ fullName: 'updated fullname' }),
);
spy.should.have.been.called.at.least(1);
});
});