diff --git a/src/client/API.ts b/src/client/API.ts index eeec1fe..7dba1d4 100644 --- a/src/client/API.ts +++ b/src/client/API.ts @@ -16,11 +16,18 @@ import { Metadata } from '@grpc/grpc-js'; import { KV, RequestWithMeta, Map } from '../types/common'; export class API { - createMetadata(request: RequestWithMeta<{}>): Metadata { + createMetadata(request: RequestWithMeta<{}>, defaultRequestMeta?: Record): Metadata { const metadata = new Metadata(); - if (!request.requestMeta) return metadata; - for (const key of Object.keys(request.requestMeta)) { - metadata.add(key, request.requestMeta[key]); + if (defaultRequestMeta) { + for (const key in defaultRequestMeta) { + metadata.add(key, defaultRequestMeta[key]); + } + } + + if (request.requestMeta) { + for (const key of Object.keys(request.requestMeta)) { + metadata.add(key, request.requestMeta[key]); + } } return metadata; } diff --git a/src/client/Cryption.ts b/src/client/Cryption.ts index f9c3d7d..e9b6b8a 100644 --- a/src/client/Cryption.ts +++ b/src/client/Cryption.ts @@ -26,6 +26,8 @@ export type DecryptResponse = { export type CryptionOptions = { componentName: string; + // set default metadata on every request + defaultRequestMeta?: Record; }; export default class Cryption extends API { @@ -50,8 +52,9 @@ export default class Cryption extends API { req.setKeyId(request.keyId); } + const metadata = this.createMetadata(request, this.options.defaultRequestMeta); return new Promise((resolve, reject) => { - this.cryptionClient.encrypt(req, this.createMetadata(request), (err, res: EncryptResponse) => { + this.cryptionClient.encrypt(req, metadata, (err, res: EncryptResponse) => { if (err) return reject(err); resolve(res.toObject()); }); @@ -63,8 +66,9 @@ export default class Cryption extends API { req.setComponentName(this.options.componentName); req.setCipherText(request.cipherText); + const metadata = this.createMetadata(request, this.options.defaultRequestMeta); return new Promise((resolve, reject) => { - this.cryptionClient.decrypt(req, this.createMetadata(request), (err, res: DecryptResponsePB) => { + this.cryptionClient.decrypt(req, metadata, (err, res: DecryptResponsePB) => { if (err) return reject(err); const plainText = Buffer.from(res.getPlainText_asB64(), 'base64'); resolve({ diff --git a/test/unit/client/Cryption.test.ts b/test/unit/client/Cryption.test.ts index 4e5d4a0..841081f 100644 --- a/test/unit/client/Cryption.test.ts +++ b/test/unit/client/Cryption.test.ts @@ -6,7 +6,7 @@ describe.skip('Cryption.test.ts', () => { const componentName = 'cryption_demo'; beforeAll(() => { - client = new Client('34904', '127.0.0.1', { cryption: { componentName } }); + client = new Client('34904', '127.0.0.1', { cryption: { componentName, defaultRequestMeta: {} } }); }); it('should encrypt and decrypt success', async () => {