-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.ts
81 lines (71 loc) · 2.48 KB
/
redis.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
import type { Profile, ProfileWithShort } from "@/types/shared"
import { Redis } from "@upstash/redis"
import { nanoid } from "@/lib/nanoid"
export type RedisResponse<T> = {
data: T
status: "error" | "success"
isOk: boolean
}
const redis = Redis.fromEnv()
// Resolver helper function
const createResponse = <R>(data: R, isOk: boolean): RedisResponse<R> => {
return {
data,
isOk,
status: isOk ? "success" : "error",
}
}
export const getShortStoreKey = (short: string) => `short.${short}`
export const getAddressShortStoreKey = (address: string) => `${address}.short`
export async function createProfile(profile: Profile) {
// get a short uid for user
const shortId = nanoid()
// get short's store key
const shortKey = getShortStoreKey(shortId)
const addressShortKey = getAddressShortStoreKey(profile.address)
return Promise.all([
// set user object mapped to it's [address]
redis.set(profile.address, profile),
// alias [address].short to [short]
redis.set(addressShortKey, shortId),
// * alias [short] to [address]
// short->address->Profile
redis.set(shortKey, profile.address),
])
}
export async function updateProfile(newProfileContent: Profile) {
const { address } = newProfileContent
return redis.set(address, newProfileContent)
}
export async function getProfileShortId(address: string) {
// get a short uid for user
const addressShortKey = getAddressShortStoreKey(address)
const userShortId = await redis.get<string>(addressShortKey)
if (userShortId) {
return createResponse(userShortId, true)
}
return createResponse(null, false)
}
export async function getProfileByShort(shortId: string) {
// get a short uid for user
const shortKey = getShortStoreKey(shortId)
const userAddress = await redis.get(shortKey)
if (userAddress) {
const profile = await redis.get<ProfileWithShort>(userAddress as string)
return createResponse({ ...profile, shortId }, true)
}
return createResponse(null, false)
}
export async function getProfileByAddress(address: string) {
const profile = await redis.get<ProfileWithShort>(address as string)
if (profile) {
const { data: shortId } = await getProfileShortId(address)
return createResponse({ ...profile, shortId }, true)
}
return createResponse(null, false)
}
export async function getProfileByShortOrAddress(userShortOrAddr: string) {
const callback =
userShortOrAddr.length > 9 ? getProfileByAddress : getProfileByShort
return await callback(userShortOrAddr)
}