-
Notifications
You must be signed in to change notification settings - Fork 48
/
azure-table.mapper.ts
55 lines (48 loc) · 1.68 KB
/
azure-table.mapper.ts
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
import { generateUuid } from '@azure/ms-rest-js';
import { Logger } from '@nestjs/common';
import { AZURE_TABLE_ENTITY } from './azure-table.decorators';
import azure = require('azure-storage');
const logger = new Logger(`AzureEntityMapper`);
export interface PartitionRowKeyValues {
RowKey: {
_: string;
$: string;
};
PartitionKey: {
_: string;
$: string;
};
}
export class AzureEntityMapper {
static serializeAll<E>(entriesDescriptor: azure.TableService.EntityMetadata[]): E[] {
return entriesDescriptor.map<E>(entry => {
return AzureEntityMapper.serialize<E>(entry);
});
}
static serialize<E>(entryDescriptor: azure.TableService.EntityMetadata) {
const result = {} as E;
for (const key in entryDescriptor) {
if (key !== '.metadata') {
result[key] = entryDescriptor[key]._;
}
}
return result;
}
static createEntity<D>(partialDto: Partial<AzureEntityMapper>, rowKeyValue = generateUuid()) {
// Note: make sure we are getting the metatadat from the DTO constructor
// See: src/table-storage/azure-table.repository.ts
const entityDescriptor = Reflect.getMetadata(AZURE_TABLE_ENTITY, partialDto.constructor) as PartitionRowKeyValues;
for (const key in partialDto) {
if (entityDescriptor[key]) {
// update the value propery
entityDescriptor[key]._ = partialDto[key];
}
}
// make sure we have a unique RowKey
entityDescriptor.RowKey._ = rowKeyValue;
logger.debug(`Mapped Entity from DTO:`);
logger.debug(`- PartitionKey=${entityDescriptor.PartitionKey._}`);
logger.debug(`- RowKey=${rowKeyValue}`);
return entityDescriptor as (D & PartitionRowKeyValues);
}
}