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