generated from Hebilicious/serverless-esbuild-template
-
Notifications
You must be signed in to change notification settings - Fork 71
/
photo.ts
87 lines (77 loc) · 2.25 KB
/
photo.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
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
85
86
87
import { DynamoDB } from "aws-sdk"
import { ulid } from "ulid"
import { Item } from "./base"
import { getClient } from "./client"
export class Photo extends Item {
username: string
url: string
photoId: string
likesCount: number
commentCount: number
constructor(username: string, url?: string, photoId: string = ulid(), likesCount?: number, commentCount?: number) {
super()
this.username = username
this.url = url
this.photoId = photoId
this.likesCount = likesCount || 0
this.commentCount = commentCount || 0
}
static fromItem(item?: DynamoDB.AttributeMap): Photo {
if (!item) throw new Error("No item!")
return new Photo(
item.username.S,
item.url.S,
item.photoId.S,
Number(item.likesCount.N),
Number(item.commentCount.N)
)
}
get pk(): string {
return `UP#${this.username}`
}
get sk(): string {
return `PHOTO#${this.photoId}`
}
toItem(): Record<string, unknown> {
return {
...this.keys(),
username: { S: this.username },
url: { S: this.url },
photoId: { S: this.photoId },
likesCount: { N: this.likesCount.toString() },
commentCount: { N: this.commentCount.toString() }
}
}
}
export const createPhoto = async (photo: Photo): Promise<Photo> => {
const client = getClient()
try {
await client
.putItem({
TableName: process.env.TABLE_NAME,
Item: photo.toItem(),
ConditionExpression: "attribute_not_exists(PK)"
})
.promise()
return photo
} catch (error) {
console.log(error)
throw error
}
}
export const getPhoto = async (username: string, photoId: string): Promise<Photo> => {
const client = getClient()
const photo = new Photo(username, "", photoId)
try {
const resp = await client
.getItem({
TableName: process.env.TABLE_NAME,
Key: photo.keys()
})
.promise()
return Photo.fromItem(resp.Item)
} catch (error) {
console.log(error)
throw error
}
}