Skip to content

Commit 64b8a18

Browse files
er-limdianeCdrPix
andcommitted
feat(api): add hash method in Module model
Co-authored-by: Diane Cordier <[email protected]>
1 parent fae6ecb commit 64b8a18

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

api/src/devcomp/domain/models/module/Module.js

+8
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import crypto from 'node:crypto';
2+
13
import { assertNotNullOrUndefined } from '../../../../shared/domain/models/asserts.js';
24
import { ModuleInstantiationError } from '../../errors.js';
35

@@ -37,6 +39,12 @@ class Module {
3739
throw new ModuleInstantiationError('A module should have a list of grains');
3840
}
3941
}
42+
43+
hash() {
44+
const hash = crypto.createHash('sha256');
45+
hash.update(JSON.stringify(this));
46+
return hash.copy().digest('hex');
47+
}
4048
}
4149

4250
export { Module };

api/tests/devcomp/unit/domain/models/module/Module_test.js

+38-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
import crypto from 'node:crypto';
2+
13
import { ModuleInstantiationError } from '../../../../../../src/devcomp/domain/errors.js';
24
import { Module } from '../../../../../../src/devcomp/domain/models/module/Module.js';
35
import { DomainError } from '../../../../../../src/shared/domain/errors.js';
4-
import { catchErrSync, expect } from '../../../../../test-helper.js';
6+
import { catchErrSync, expect, sinon } from '../../../../../test-helper.js';
57

68
describe('Unit | Devcomp | Domain | Models | Module | Module', function () {
79
describe('#constructor', function () {
@@ -138,4 +140,39 @@ describe('Unit | Devcomp | Domain | Models | Module | Module', function () {
138140
});
139141
});
140142
});
143+
144+
describe('#hash', function () {
145+
it('returns hash of module content', function () {
146+
// given
147+
const id = 1;
148+
const slug = 'les-adresses-email';
149+
const title = 'Les adresses email';
150+
const isBeta = false;
151+
const grains = [Symbol('text')];
152+
const transitionTexts = [];
153+
const details = Symbol('details');
154+
const module = new Module({ id, slug, title, isBeta, grains, details, transitionTexts });
155+
const hashedResult = 'AZERTY123456';
156+
157+
const digestStub = sinon.stub().returns(hashedResult);
158+
const updateStub = sinon.stub();
159+
const createHashStub = sinon.stub(crypto, 'createHash').returns({
160+
copy: () => {
161+
return {
162+
digest: digestStub,
163+
};
164+
},
165+
update: updateStub,
166+
});
167+
168+
// when
169+
const result = module.hash();
170+
171+
// then
172+
expect(result).to.deep.equal(hashedResult);
173+
expect(createHashStub).to.have.been.calledOnceWith('sha256');
174+
expect(updateStub).to.have.been.calledOnceWith(JSON.stringify(module));
175+
expect(digestStub).to.have.been.calledOnceWith('hex');
176+
});
177+
});
141178
});

0 commit comments

Comments
 (0)