-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
utils.ts
63 lines (54 loc) · 1.92 KB
/
utils.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
import { createHash } from "crypto";
import { Job, JobPayload, PartialJobPayload } from "./job";
export function encode(
object: Record<string, unknown> | Array<Record<string, unknown>>
): string {
return JSON.stringify(object);
}
export function encodeArray(object: Array<Record<string, unknown>>): string {
return JSON.stringify(object);
}
export function sleep(ms: number, value?: unknown): Promise<unknown> {
return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}
/**
* wraps things that are not errors in an error object
* @param {*} object likely a string that was thrown instead of an error
* @return {Error} an error with a warning about throwing non-errors
* @private
*/
export function wrapNonErrors(object: string | Error | undefined): Error {
if (object instanceof Error) return object;
console.warn(`
Job failed without providing an error.
Ensure your promise was rejected with an *Error* and not a *String*
correct:\treject(new Error('message'))
incorrect:\treject('message')
`);
return new Error(object || "Job failed with no error or message given");
}
/**
* hashes the password with server-provided salt
* @param {String} password the password to the faktory server
* @param {String} salt the server-provided salt to use in hashing
* @param {Number} iterations the number of time to apply the salt
* @return {String} the password hash
* @private
*/
export function hash(
password: string,
salt: string,
iterations: number
): string {
let hash = createHash("sha256").update(`${password}${salt}`);
for (let i = 1; i < iterations; i += 1) {
hash = createHash("sha256").update(hash.digest());
}
return hash.digest("hex");
}
export function toJobPayloadWithDefaults(
job: Job | PartialJobPayload
): JobPayload {
const payload = "toJSON" in job ? (job as Job).toJSON() : job;
return Object.assign({ jid: Job.jid() }, Job.defaults, payload);
}