alpha release
update v0.8.0
This commit is contained in:
88
src/lib/utils.ts
Normal file
88
src/lib/utils.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
/**
|
||||
*
|
||||
* @param userId
|
||||
* @param secret
|
||||
* @returns
|
||||
*/
|
||||
export const generateAccessToken = (userId: string, secret = '') =>
|
||||
jwt.sign({ id: userId }, secret, { expiresIn: '10m' });
|
||||
|
||||
/**
|
||||
*
|
||||
* @param val
|
||||
* @returns
|
||||
*/
|
||||
export const generateEtag = (val: string) =>
|
||||
crypto.createHash('sha256').update(val).digest('hex');
|
||||
|
||||
/**
|
||||
*
|
||||
* @param userId
|
||||
* @param secret
|
||||
* @param extendRefresh
|
||||
* @returns
|
||||
*/
|
||||
export const generateRefreshToken = (
|
||||
userId: string,
|
||||
secret = '',
|
||||
extendRefresh = false
|
||||
) => {
|
||||
const tokenId = uuidv4(); // unique ID for the refresh token
|
||||
|
||||
const token = jwt.sign({ id: userId, tokenId }, secret, {
|
||||
expiresIn: extendRefresh ? '7d' : '1h',
|
||||
});
|
||||
|
||||
return token;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param value
|
||||
* @returns
|
||||
*/
|
||||
export const getQueryParameterArray = (value: unknown | unknown[] = []) =>
|
||||
Array.isArray(value)
|
||||
? value.map((val) => `${val}`.trim())
|
||||
: [`${value}`.trim()];
|
||||
|
||||
/**
|
||||
*
|
||||
* @param value
|
||||
* @returns
|
||||
*/
|
||||
export const getValueOrFirstEntry = (value: string | string[]) =>
|
||||
Array.isArray(value) && value.length ? value[0] : value;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param filePath
|
||||
* @returns
|
||||
*/
|
||||
export const loadObjectFromJson = async (filePath: string) => {
|
||||
const contents = await readFile(filePath, { encoding: 'utf8' });
|
||||
return JSON.parse(contents);
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param contents
|
||||
* @param filePath
|
||||
*/
|
||||
export const saveToJson = async (
|
||||
contents: object | string,
|
||||
filePath: string
|
||||
) => {
|
||||
const stringContents =
|
||||
typeof contents === 'string' ? contents : JSON.stringify(contents, null, 2);
|
||||
|
||||
await writeFile(filePath, stringContents, {
|
||||
encoding: 'utf8',
|
||||
flag: 'w',
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user