@milkio/redis 1.0.0-alpha.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ {
2
+ "enableReleases": false,
3
+ "githubOwner": "akirarika",
4
+ "githubRepo": "milkio",
5
+ "giteeOwner": "akirarika",
6
+ "giteeRepo": "milkio"
7
+ }
package/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # milkio-redis
2
+
3
+ To install dependencies:
4
+
5
+ ```bash
6
+ bun install
7
+ ```
8
+
9
+ To run:
10
+
11
+ ```bash
12
+ bun run index.ts
13
+ ```
14
+
15
+ This project was created using `bun init` in bun v1.1.30. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
package/bun.lockb ADDED
Binary file
package/index.ts ADDED
@@ -0,0 +1,110 @@
1
+ import type { RedisClientOptions } from 'redis'
2
+ import { TSON } from '@southern-aurora/tson'
3
+
4
+ export async function createRedis<Options extends RedisClientOptions>(options: Options) {
5
+ const NodeRedis = await import('redis')
6
+ const redis = await NodeRedis.default.createClient(options).connect()
7
+
8
+ const milkioRedis = {
9
+ raw: redis,
10
+ useCache: <T>(key: string, defaultValue: T | undefined = undefined) => ({
11
+ set: async (value: T, expireMs: number): Promise<T> => {
12
+ await redis.PSETEX(key, expireMs, TSON.stringify(value))
13
+ return value
14
+ },
15
+ get: async (): Promise<undefined | T> => {
16
+ const result = await redis.GET(key)
17
+ if (result === null) return defaultValue
18
+ return TSON.parse(result)
19
+ },
20
+ pull: async () => {
21
+ const resultRaw = await redis.MULTI().GET(key).DEL(key).EXEC()
22
+ const result = resultRaw[0]
23
+ if (result === null) return defaultValue
24
+ return TSON.parse(result as string)
25
+ },
26
+ has: async (): Promise<boolean> => {
27
+ const result = await redis.GET(key)
28
+ return result !== null
29
+ },
30
+ del: async () => {
31
+ await redis.DEL(key)
32
+ },
33
+ }),
34
+ useCount: (key: string) => ({
35
+ get: async (): Promise<number> => {
36
+ const result = await redis.GET(key)
37
+ return result ? Number(result) : 0
38
+ },
39
+ add: async (amount: number, expireMs?: number): Promise<number> => {
40
+ if (!expireMs) {
41
+ const result = await redis.INCRBY(key, amount)
42
+ return result
43
+ }
44
+ else {
45
+ const result = await redis.MULTI().INCRBY(key, amount).PEXPIRE(key, expireMs).EXEC()
46
+ return Number(result[0])
47
+ }
48
+ },
49
+ sub: async (key: string, amount: number): Promise<number> => {
50
+ const result = await redis.DECRBY(key, amount)
51
+ return result
52
+ },
53
+ }),
54
+ useResultCache: async <Handler extends () => unknown | Promise<unknown>>(key: string, expireMs: number, handler: Handler, options?: { realExpireMs?: number, lockInterval?: number }): Promise<Awaited<ReturnType<Handler>>> => {
55
+ const resultRaw = await redis.get(key)
56
+ if (resultRaw) {
57
+ const result: { T: number, R: any } = TSON.parse(resultRaw)
58
+ if (result.T > new Date().getTime()) return result.R
59
+ const lock = await redis.GET(`${key}:lock`)
60
+ if (lock === '1') return result.R
61
+ await redis.PSETEX(`${key}:lock`, options?.lockInterval ?? 6000, '1')
62
+ }
63
+ const result = { R: (await handler()) as Awaited<ReturnType<Handler>>, T: new Date().getTime() + expireMs }
64
+ await redis.PSETEX(key, expireMs + (options?.realExpireMs ?? expireMs + Math.floor(expireMs * Math.random())) + (options?.lockInterval ?? 6000), TSON.stringify(result))
65
+
66
+ return result.R
67
+ },
68
+ useClockIn: (key: string, cleanDate: Date) => ({
69
+ clockIn: async (offset: number): Promise<void> => {
70
+ await redis.MULTI().SETBIT(key, offset, 1).PEXPIREAT(key, cleanDate.getTime()).EXEC()
71
+ },
72
+ check: async (offset: number): Promise<boolean> => {
73
+ const result = await redis.GETBIT(key, offset)
74
+ return result === 1
75
+ },
76
+ firstClockIn: async (): Promise<number> => {
77
+ const result = await redis.BITPOS(key, 1)
78
+ return result
79
+ },
80
+ lastClockIn: async (): Promise<number> => {
81
+ const result = await redis.BITPOS(key, 1, -1)
82
+ return result
83
+ },
84
+ toArray: async (length: number): Promise<boolean[]> => {
85
+ const resultRaw = await redis.BITFIELD(key, [
86
+ {
87
+ operation: 'GET',
88
+ encoding: `u${length}`,
89
+ offset: `#0`,
90
+ },
91
+ ])
92
+ const result = Number.parseInt(`${resultRaw}`).toString(2).split('')
93
+ const fill = []
94
+ for (let i = 0; i < length - result.length; i++) fill.push('0')
95
+ return [...fill, ...result].map(v => (v === '1'))
96
+ },
97
+ count: async (): Promise<number> => {
98
+ const result = await redis.BITCOUNT(key)
99
+ return result
100
+ },
101
+ clean: async (): Promise<void> => {
102
+ await redis.DEL(key)
103
+ },
104
+ }),
105
+ }
106
+
107
+ return milkioRedis
108
+ }
109
+
110
+ export type Redis = Awaited<ReturnType<typeof createRedis>>
package/package.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "@milkio/redis",
3
+ "type": "module",
4
+ "version": "1.0.0-alpha.100",
5
+ "module": "index.ts",
6
+ "devDependencies": {
7
+ "@southern-aurora/tson": "*",
8
+ "@types/bun": "latest",
9
+ "redis": "^4.7.0"
10
+ }
11
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "jsx": "react-jsx",
5
+ "erasableSyntaxOnly":true,
6
+ // Enable latest features
7
+ "lib": ["ESNext", "DOM"],
8
+ "moduleDetection": "force",
9
+ "module": "ESNext",
10
+
11
+ // Bundler mode
12
+ "moduleResolution": "bundler",
13
+ "allowImportingTsExtensions": true,
14
+ "allowJs": true,
15
+
16
+ // Best practices
17
+ "strict": true,
18
+ "noFallthroughCasesInSwitch": true,
19
+
20
+ "noPropertyAccessFromIndexSignature": false,
21
+ // Some stricter flags (disabled by default)
22
+ "noUnusedLocals": false,
23
+ "noUnusedParameters": false,
24
+ "noEmit": true,
25
+ "verbatimModuleSyntax": true,
26
+ "skipLibCheck": true
27
+ }
28
+ }