-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathmodel-with-custom-mapper-for-sort-key.model.ts
53 lines (41 loc) · 1.53 KB
/
model-with-custom-mapper-for-sort-key.model.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
// tslint:disable:max-classes-per-file
import { MapperForType, Model, NumberAttribute, PartitionKey, Property, SortKey } from '../../src/dynamo-easy'
export class CustomId {
private static MULTIPLIER_E = 5
date: Date
id: number
static parse(value: string): CustomId {
const id = parseInt(value.substr(0, value.length - CustomId.MULTIPLIER_E), 10)
const date = value.substr(value.length - CustomId.MULTIPLIER_E)
const y = date.toString().substr(0, 4)
const m = date.toString().substr(4, 2)
const d = date.toString().substr(6, 2)
return new CustomId(new Date(`${y}-${m}-${d}`), id)
}
static unparse(customId: CustomId): string {
const yyyy = customId.date.getUTCFullYear()
const mm = (<any>(customId.date.getUTCMonth() + 1).toString()).padStart(2, '0')
const dd = (<any>customId.date.getUTCDate().toString()).padStart(2, '0')
return `${yyyy}${mm}${dd}${(<any>customId.id.toString()).padStart(CustomId.MULTIPLIER_E, '0')}`
}
constructor(date: Date, id: number) {
this.date = date
this.id = id
}
}
export const CustomIdMapper: MapperForType<CustomId, NumberAttribute> = {
fromDb: (attributeValue: NumberAttribute) => CustomId.parse(attributeValue.N),
toDb: (propertyValue: CustomId) => ({ N: CustomId.unparse(propertyValue) }),
}
@Model()
export class ModelWithCustomMapperForSortKeyModel {
@PartitionKey()
name: string
@SortKey()
@Property({ mapper: CustomIdMapper })
customId: CustomId
constructor(name: string, id: CustomId) {
this.name = name
this.customId = id
}
}