generated from hyper63/adapter-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
62 lines (53 loc) · 1.61 KB
/
utils.ts
File metadata and controls
62 lines (53 loc) · 1.61 KB
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
// deno-lint-ignore-file no-explicit-any
import { hmac } from './deps.js'
type Fn<Arguments extends unknown[]> = (...args: Arguments) => any
type PromiseWrap<X> = X extends Promise<any> ? X
: Promise<X>
export class Queue {
#_queue: [fn: any, args: any[], resolve: any, reject: any][] = []
#_isRunning = false
#autostart: boolean
public constructor(autostart: boolean = true) {
this.#autostart = autostart
}
public push<Arguments extends unknown[], Callback extends Fn<Arguments>>(
fn: Callback,
...args: Arguments
): PromiseWrap<ReturnType<Callback>> {
return new Promise((resolve, reject) => {
this.#_queue.push([fn, args, resolve, reject])
if (!this.#_isRunning && this.#autostart) this._run()
}) as any
}
public start() {
this.#autostart = true
this._run()
}
public stop() {
this.#autostart = false
this.#_isRunning = false
}
private _run() {
if (this.#_isRunning || this.#_queue.length < 1) return
this.#_isRunning = true
;(async () => {
let value = this.#_queue.shift()
while (this.#_isRunning && value !== undefined) {
const [fn, args, resolve, reject] = value
try {
const value = await fn(...args)
resolve(value)
} catch (error) {
reject(error)
}
value = this.#_queue.shift()
}
this.#_isRunning = false
})()
}
}
export const computeSignature = (secret: string, payload: unknown, time: number) => {
const msg = `${time}.${JSON.stringify(payload, null, 0)}`
const signature = hmac('sha256', secret, msg, 'utf8', 'hex')
return signature
}