-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
31 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,40 @@ | ||
import { Redis } from "ioredis"; | ||
import _ from "lodash"; | ||
|
||
const key = "field:data"; | ||
const fieldKey = "field:data"; | ||
const sessionKey = "user:sessions"; | ||
|
||
function getClient() { | ||
return new Redis(process.env["REDIS_URL"]!, { family: 6 }); | ||
} | ||
const redis = new Redis(process.env["REDIS_URL"]!, { family: 6 }); | ||
|
||
export async function decodeData() { | ||
const redis = getClient(); | ||
const value = await redis.get(key); | ||
const value = await redis.get(fieldKey); | ||
if (typeof value !== "string" || !value) { | ||
throw new Error(`unexpected data on key: ${key}`); | ||
throw new Error(`unexpected data on key: ${fieldKey}`); | ||
} | ||
return Array.from(value, (char) => char.charCodeAt(0)); | ||
} | ||
|
||
export async function encodeData(value: number[]) { | ||
const redis = getClient(); | ||
const binaryString = Buffer.from(value).toString("binary"); | ||
await redis.set(key, binaryString); | ||
await redis.set(fieldKey, binaryString); | ||
return value; | ||
} | ||
|
||
export async function getSession(sessionId: string) { | ||
const value = await redis.hget(sessionKey, sessionId); | ||
return value === "alive" || value === "dead" ? value : null; | ||
} | ||
|
||
export async function startSession(sessionId: string) { | ||
return redis.hset(sessionKey, sessionId, "alive"); | ||
} | ||
|
||
export async function killSession(sessionId: string) { | ||
return redis.hset(sessionKey, sessionId, "dead"); | ||
} | ||
|
||
export async function reviveSessions() { | ||
const sessions = await redis.hkeys(sessionKey); | ||
const args = sessions.flatMap((sessionId) => [sessionId, "alive"]); | ||
redis.hset(sessionKey, ...args); | ||
} |