repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
braintrust-proxy
github_2023
braintrustdata
typescript
FlushingExporter.constructor
constructor(private flushFn: (resourceMetrics: any) => Promise<Response>) { super({ aggregationSelector: (_instrumentType) => Aggregation.Default(), aggregationTemporalitySelector: (_instrumentType) => AggregationTemporality.CUMULATIVE, }); }
/** * Constructor * @param config Exporter configuration * @param callback Callback to be called after a server was started */
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/packages/proxy/edge/exporter.ts#L14-L20
87c174af68cfc37e884ea36f551e99b8336e5949
braintrust-proxy
github_2023
braintrustdata
typescript
FlushingExporter.onShutdown
override async onShutdown(): Promise<void> { // do nothing }
/** * Shuts down the export server and clears the registry */
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/packages/proxy/edge/exporter.ts#L46-L48
87c174af68cfc37e884ea36f551e99b8336e5949
braintrust-proxy
github_2023
braintrustdata
typescript
handleOptions
async function handleOptions( request: Request, corsHeaders: Record<string, string>, ) { if ( request.headers.get("Origin") !== null && request.headers.get("Access-Control-Request-Method") !== null && request.headers.get("Access-Control-Request-Headers") !== null ) { // Handle CORS preflight req...
// https://developers.cloudflare.com/workers/examples/cors-header-proxy/
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/packages/proxy/edge/index.ts#L77-L103
87c174af68cfc37e884ea36f551e99b8336e5949
braintrust-proxy
github_2023
braintrustdata
typescript
escapeAttributeValue
function escapeAttributeValue(str: MetricAttributeValue = "") { if (typeof str !== "string") { str = JSON.stringify(str); } return escapeString(str).replace(/"/g, '\\"'); }
/** * String Attribute values are converted directly to Prometheus attribute values. * Non-string values are represented as JSON-encoded strings. * * `undefined` is converted to an empty string. */
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/packages/proxy/src/PrometheusSerializer.ts#L54-L59
87c174af68cfc37e884ea36f551e99b8336e5949
braintrust-proxy
github_2023
braintrustdata
typescript
sanitizePrometheusMetricName
function sanitizePrometheusMetricName(name: string): string { // replace all invalid characters with '_' return name .replace(invalidCharacterRegex, "_") .replace(multipleUnderscoreRegex, "_"); }
/** * Ensures metric names are valid Prometheus metric names by removing * characters allowed by OpenTelemetry but disallowed by Prometheus. * * https://prometheus.io/docs/concepts/data_model/#metric-names-and-attributes * * 1. Names must match `[a-zA-Z_:][a-zA-Z0-9_:]*` * * 2. Colons are reserved for user defi...
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/packages/proxy/src/PrometheusSerializer.ts#L82-L87
87c174af68cfc37e884ea36f551e99b8336e5949
braintrust-proxy
github_2023
braintrustdata
typescript
enforcePrometheusNamingConvention
function enforcePrometheusNamingConvention( name: string, type: InstrumentType, ): string { // Prometheus requires that metrics of the Counter kind have "_total" suffix if (!name.endsWith("_total") && type === InstrumentType.COUNTER) { name = name + "_total"; } return name; }
/** * @private * * Helper method which assists in enforcing the naming conventions for metric * names in Prometheus * @param name the name of the metric * @param type the kind of metric * @returns string */
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/packages/proxy/src/PrometheusSerializer.ts#L98-L108
87c174af68cfc37e884ea36f551e99b8336e5949
braintrust-proxy
github_2023
braintrustdata
typescript
createEmptyReadableStream
function createEmptyReadableStream(): ReadableStream { return new ReadableStream({ start(controller) { controller.close(); }, }); }
// The following functions are copied (with some modifications) from @vercel/ai
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/packages/proxy/src/proxy.ts#L1752-L1758
87c174af68cfc37e884ea36f551e99b8336e5949
braintrust-proxy
github_2023
braintrustdata
typescript
parseEnumHeader
function parseEnumHeader<T>( headerName: string, headerTypes: readonly T[], value?: string, ): (typeof headerTypes)[number] { const header = value && value.toLowerCase(); if (header && !headerTypes.includes(header as T)) { throw new ProxyBadRequestError( `Invalid ${headerName} header '${header}'. Mu...
// --------------------------------------------------
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/packages/proxy/src/proxy.ts#L1849-L1863
87c174af68cfc37e884ea36f551e99b8336e5949
braintrust-proxy
github_2023
braintrustdata
typescript
pack
function pack(size: 0 | 1, arg: number) { return new Uint8Array( size === 0 ? [arg, arg >> 8] : [arg, arg >> 8, arg >> 16, arg >> 24], ); }
/** * Pack a number into a byte array. * @param size Pass `0` for 16-bit output, or `1` for 32-bit output. Large * values will be truncated. * @param arg Integer to pack. * @returns Byte array with the integer. */
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/packages/proxy/utils/audioEncoder.ts#L92-L96
87c174af68cfc37e884ea36f551e99b8336e5949
braintrust-proxy
github_2023
braintrustdata
typescript
cacheGet
const cacheGet = async ( encryptionKey: string, key: string, ): Promise<string | null> => encryptionKey === cacheEncryptionKey && key === credentialId ? JSON.stringify(credentialCacheValue) : null;
// Valid JWT, valid cache.
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/packages/proxy/utils/tempCredentials.test.ts#L192-L198
87c174af68cfc37e884ea36f551e99b8336e5949
braintrust-proxy
github_2023
braintrustdata
typescript
badCacheGet
const badCacheGet = async () => null;
// Valid JWT, failed cache call.
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/packages/proxy/utils/tempCredentials.test.ts#L206-L206
87c174af68cfc37e884ea36f551e99b8336e5949
braintrust-proxy
github_2023
braintrustdata
typescript
wrongSecretCacheGet
const wrongSecretCacheGet = async () => `{ "authToken": "wrong auth token" }`;
// Incorrect signature, nonnull cache response.
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/packages/proxy/utils/tempCredentials.test.ts#L212-L212
87c174af68cfc37e884ea36f551e99b8336e5949
pylon
github_2023
getcronit
typescript
isCommandAvailable
function isCommandAvailable(command: string): boolean { try { execSync(`${command} --version`, {stdio: 'ignore'}) return true } catch (e) { console.error(e) return false } }
// Helper function to check if a command exists
https://github.com/getcronit/pylon/blob/d428f8a1f98c7973872c222371d11557dd84acbf/packages/create-pylon/src/detect-pm.ts#L8-L16
d428f8a1f98c7973872c222371d11557dd84acbf
pylon
github_2023
getcronit
typescript
isBun
function isBun(): boolean { // @ts-ignore: Bun may not be defined return typeof Bun !== 'undefined' && isCommandAvailable('bun') }
// Detect Bun
https://github.com/getcronit/pylon/blob/d428f8a1f98c7973872c222371d11557dd84acbf/packages/create-pylon/src/detect-pm.ts#L19-L22
d428f8a1f98c7973872c222371d11557dd84acbf
pylon
github_2023
getcronit
typescript
isNpm
function isNpm(): boolean { return process.env.npm_execpath?.includes('npm') ?? false }
// Detect npm
https://github.com/getcronit/pylon/blob/d428f8a1f98c7973872c222371d11557dd84acbf/packages/create-pylon/src/detect-pm.ts#L25-L27
d428f8a1f98c7973872c222371d11557dd84acbf
pylon
github_2023
getcronit
typescript
isYarn
function isYarn(): boolean { return process.env.npm_execpath?.includes('yarn') ?? false }
// Detect Yarn
https://github.com/getcronit/pylon/blob/d428f8a1f98c7973872c222371d11557dd84acbf/packages/create-pylon/src/detect-pm.ts#L30-L32
d428f8a1f98c7973872c222371d11557dd84acbf
pylon
github_2023
getcronit
typescript
isDeno
function isDeno(): boolean { // @ts-ignore: Deno may not be defined return typeof Deno !== 'undefined' && isCommandAvailable('deno') }
// Detect Deno
https://github.com/getcronit/pylon/blob/d428f8a1f98c7973872c222371d11557dd84acbf/packages/create-pylon/src/detect-pm.ts#L35-L38
d428f8a1f98c7973872c222371d11557dd84acbf
pylon
github_2023
getcronit
typescript
isPnpm
function isPnpm(): boolean { return process.env.npm_execpath?.includes('pnpm') ?? false }
// Detect pnpm
https://github.com/getcronit/pylon/blob/d428f8a1f98c7973872c222371d11557dd84acbf/packages/create-pylon/src/detect-pm.ts#L41-L43
d428f8a1f98c7973872c222371d11557dd84acbf
pylon
github_2023
getcronit
typescript
detectByLockFiles
function detectByLockFiles(cwd: string): PackageManager | null { if (fs.existsSync(path.join(cwd, 'bun.lockb'))) { return 'bun' } if (fs.existsSync(path.join(cwd, 'package-lock.json'))) { return 'npm' } if (fs.existsSync(path.join(cwd, 'yarn.lock'))) { return 'yarn' } if ( fs.existsSync(pa...
// Detect based on lock files
https://github.com/getcronit/pylon/blob/d428f8a1f98c7973872c222371d11557dd84acbf/packages/create-pylon/src/detect-pm.ts#L46-L66
d428f8a1f98c7973872c222371d11557dd84acbf
pylon
github_2023
getcronit
typescript
SchemaParser.extractForbiddenFieldNamesFromSchema
private extractForbiddenFieldNamesFromSchema(): void { // Define a regular expression to check if a field name is a valid GraphQL field name. const validFieldNameRegExp = /^[_A-Za-z][_0-9A-Za-z]*$/ // Define a helper function to check if a field name is reserved. const isReserved = (name: string): bool...
/** * Extracts reserved field names from the schema by removing them from their respective types and inputs. */
https://github.com/getcronit/pylon/blob/d428f8a1f98c7973872c222371d11557dd84acbf/packages/pylon-builder/src/schema/schema-parser.ts#L685-L726
d428f8a1f98c7973872c222371d11557dd84acbf
pylon
github_2023
getcronit
typescript
isReserved
const isReserved = (name: string): boolean => { if (!validFieldNameRegExp.test(name)) { // console.warn( // `\x1b[33mWarning: forbidden field name "${name}" detected\x1b[0m` // ) return true } // Fields starting with "__" are considered reserved. return name.sta...
// Define a helper function to check if a field name is reserved.
https://github.com/getcronit/pylon/blob/d428f8a1f98c7973872c222371d11557dd84acbf/packages/pylon-builder/src/schema/schema-parser.ts#L690-L699
d428f8a1f98c7973872c222371d11557dd84acbf
pylon
github_2023
getcronit
typescript
getEnv
const getEnv = async (...args) => await import('@getcronit/pylon').then(m => m.getEnv(...args)).catch(() => process.env)
// @ts-ignore
https://github.com/getcronit/pylon/blob/d428f8a1f98c7973872c222371d11557dd84acbf/packages/pylon-telemetry/src/index.ts#L12-L12
d428f8a1f98c7973872c222371d11557dd84acbf
pylon
github_2023
getcronit
typescript
rootGraphqlResolver
const rootGraphqlResolver = (fn: Function | object | Promise<Function> | Promise<object>) => async ( _: object, args: Record<string, any>, ctx: Context, info: GraphQLResolveInfo ) => { return Sentry.withScope(async scope => { const ctx = asyncContext.getStore() ...
// Define a root resolver function that maps a given resolver function or object to a GraphQL resolver.
https://github.com/getcronit/pylon/blob/d428f8a1f98c7973872c222371d11557dd84acbf/packages/pylon/src/define-pylon.ts#L170-L271
d428f8a1f98c7973872c222371d11557dd84acbf
visualisations
github_2023
samwho
typescript
shift
function shift(year: number) { return year - 1982; }
// Taken from https://github.com/colin-scott/interactive_latencies/blob/master/interactive_latency.html
https://github.com/samwho/visualisations/blob/00ec9f342b1faf0a86bc327f150f5e49ffa0bc03/numbers/src/ColinMaths.ts#L3-L5
00ec9f342b1faf0a86bc327f150f5e49ffa0bc03
visualisations
github_2023
samwho
typescript
Tweens.endFor
public static endFor(obj: any) { for (const tween of Tweens.for(obj)) { tween.end(); } }
// biome-ignore lint/suspicious/noExplicitAny: genuinely could be any
https://github.com/samwho/visualisations/blob/00ec9f342b1faf0a86bc327f150f5e49ffa0bc03/turing/core/Tweens.ts#L19-L23
00ec9f342b1faf0a86bc327f150f5e49ffa0bc03
visualisations
github_2023
samwho
typescript
Tweens.for
public static for(object: any): Tween[] { return Tweens.instance.tweens.filter( // @ts-expect-error accessing private object, I accept the risk (tween) => tween._object === object, ); }
// biome-ignore lint/suspicious/noExplicitAny: genuinely could be any
https://github.com/samwho/visualisations/blob/00ec9f342b1faf0a86bc327f150f5e49ffa0bc03/turing/core/Tweens.ts#L26-L31
00ec9f342b1faf0a86bc327f150f5e49ffa0bc03
visualisations
github_2023
samwho
typescript
Compiler.text2program
public static text2program(input: string): Program { const program: Program = {}; const parsed = parse(input.trim()); let id = 1; for (const branch of parsed) { const { label, read, instructions, index } = branch; if (!program[label.text]) { program[label.text] = {}; } if...
// 1 | 1 | P(0) L -> 0
https://github.com/samwho/visualisations/blob/00ec9f342b1faf0a86bc327f150f5e49ffa0bc03/turing/machine/Compiler.ts#L111-L137
00ec9f342b1faf0a86bc327f150f5e49ffa0bc03
router
github_2023
kitbagjs
typescript
DuplicateNamesError.constructor
public constructor(name: string) { super(`Invalid Name "${name}": Router does not support multiple routes with the same name. All name names must be unique.`) }
/** * Constructs a new DuplicateNamesError instance with a message indicating the problematic name. * @param name - The name of the name that was duplicated. */
https://github.com/kitbagjs/router/blob/9969331ba935630eba1e8cd31492ad5ad9eec7cc/src/errors/duplicateNamesError.ts#L10-L12
9969331ba935630eba1e8cd31492ad5ad9eec7cc
router
github_2023
kitbagjs
typescript
DuplicateParamsError.constructor
public constructor(paramName: string) { super(`Invalid Param "${paramName}": Router does not support multiple params by the same name. All param names must be unique.`) }
/** * Constructs a new DuplicateParamsError instance with a message indicating the problematic parameter. * @param paramName - The name of the parameter that was duplicated. */
https://github.com/kitbagjs/router/blob/9969331ba935630eba1e8cd31492ad5ad9eec7cc/src/errors/duplicateParamsError.ts#L12-L14
9969331ba935630eba1e8cd31492ad5ad9eec7cc
router
github_2023
kitbagjs
typescript
UseRouteInvalidError.constructor
public constructor(routeName: string, actualRouteName: string) { super(`useRoute called with incorrect route. Given ${routeName}, expected ${actualRouteName}`) }
/** * Constructs a new UseRouteInvalidError instance with a message that specifies both the given and expected route names. * This detailed error message aids in quickly identifying and resolving mismatches in route usage. * @param routeName - The route name that was incorrectly used. * @param actualRouteNa...
https://github.com/kitbagjs/router/blob/9969331ba935630eba1e8cd31492ad5ad9eec7cc/src/errors/useRouteInvalidError.ts#L12-L14
9969331ba935630eba1e8cd31492ad5ad9eec7cc
router
github_2023
kitbagjs
typescript
getHooksForLifecycle
function getHooksForLifecycle<T extends BeforeRouteHookLifecycle | AfterRouteHookLifecycle>(lifecycle: T, options: RouterOptions, plugins: RouterPlugin[]) { const hooks = [ options[lifecycle], ...plugins.map((plugin) => plugin[lifecycle]), ].flat().filter((hook) => hook !== undefined) return hooks }
// This is more accurate to just let typescript infer the type
https://github.com/kitbagjs/router/blob/9969331ba935630eba1e8cd31492ad5ad9eec7cc/src/services/getGlobalHooksForRouter.ts#L21-L28
9969331ba935630eba1e8cd31492ad5ad9eec7cc
router
github_2023
kitbagjs
typescript
getQueryParams
function getQueryParams(query: WithParams, url: string): Record<string, unknown> { const values: Record<string, unknown> = {} const routeSearch = new URLSearchParams(query.value) const actualSearch = new URLSearchParams(url) for (const [key, value] of Array.from(routeSearch.entries())) { const paramName = ...
/** * This function has unique responsibilities not accounted for by getParams thanks to URLSearchParams * * 1. Find query values when other query params are omitted or in a different order * 2. Find query values based on the url search key, which might not match the param name */
https://github.com/kitbagjs/router/blob/9969331ba935630eba1e8cd31492ad5ad9eec7cc/src/services/paramValidation.ts#L52-L70
9969331ba935630eba1e8cd31492ad5ad9eec7cc
router
github_2023
kitbagjs
typescript
getZodInstances
async function getZodInstances() { const { ZodSchema, ZodString, ZodBoolean, ZodDate, ZodNumber, ZodLiteral, ZodObject, ZodEnum, ZodNativeEnum, ZodArray, ZodTuple, ZodUnion, ZodDiscriminatedUnion, ZodRecord, ZodMap, ZodSet, ZodIntersection, ZodPr...
// inferring the return type is preferred for this function
https://github.com/kitbagjs/router/blob/9969331ba935630eba1e8cd31492ad5ad9eec7cc/src/services/zod.ts#L14-L58
9969331ba935630eba1e8cd31492ad5ad9eec7cc
router
github_2023
kitbagjs
typescript
sortZodSchemas
function sortZodSchemas(schemaA: ZodSchema, schemaB: ZodSchema): number { return zod?.ZodString && schemaA instanceof zod.ZodString ? 1 : zod?.ZodString && schemaB instanceof zod.ZodString ? -1 : 0 }
// Sorts string schemas last
https://github.com/kitbagjs/router/blob/9969331ba935630eba1e8cd31492ad5ad9eec7cc/src/services/zod.ts#L138-L140
9969331ba935630eba1e8cd31492ad5ad9eec7cc
router
github_2023
kitbagjs
typescript
isNotConstructor
function isNotConstructor(value: Param): boolean { return value !== String && value !== Boolean && value !== Number && value !== Date }
/** * Determines if a given value is not a constructor for String, Boolean, Date, or Number. * @param value - The value to check. * @returns True if the value is not a constructor function for String, Boolean, Date, or Number. */
https://github.com/kitbagjs/router/blob/9969331ba935630eba1e8cd31492ad5ad9eec7cc/src/types/params.ts#L16-L18
9969331ba935630eba1e8cd31492ad5ad9eec7cc
HyperAgent
github_2023
FSoft-AI4Code
typescript
commandHandler
const commandHandler = (command:string) => { const config = vscode.workspace.getConfiguration('chatgpt'); const prompt = config.get(command) as string; provider.search(prompt); };
// Register the commands that can be called from the extension's package.json
https://github.com/FSoft-AI4Code/HyperAgent/blob/c3092f2601ab3bf7f890fac2cd5b1290d3f59256/hyperagent-ext/src/extension.ts#L40-L44
c3092f2601ab3bf7f890fac2cd5b1290d3f59256
HyperAgent
github_2023
FSoft-AI4Code
typescript
ChatGPTViewProvider.constructor
constructor(private readonly _extensionUri: vscode.Uri) { this.connectWebSocket(); }
// In the constructor, we store the URI of the extension
https://github.com/FSoft-AI4Code/HyperAgent/blob/c3092f2601ab3bf7f890fac2cd5b1290d3f59256/hyperagent-ext/src/extension.ts#L165-L167
c3092f2601ab3bf7f890fac2cd5b1290d3f59256
HyperAgent
github_2023
FSoft-AI4Code
typescript
ChatGPTViewProvider.handleIncomingMessage
private handleIncomingMessage(data: WebSocket.Data): void { const parsedData = JSON.parse(data.toString()); if (parsedData.message && parsedData.message.content) { const response = parsedData.message.content; const agent = parsedData.sender const is_internal = parsedData.internal const _summary = parsed...
// Method to handle incoming messages
https://github.com/FSoft-AI4Code/HyperAgent/blob/c3092f2601ab3bf7f890fac2cd5b1290d3f59256/hyperagent-ext/src/extension.ts#L215-L243
c3092f2601ab3bf7f890fac2cd5b1290d3f59256
ptocode
github_2023
uuu555552
typescript
fileToDataURL
function fileToDataURL(file: File) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = (error) => reject(error); reader.readAsDataURL(file); }); }
// TODO: Move to a separate file
https://github.com/uuu555552/ptocode/blob/e349205f0734e37ffd496135038100ac551462dd/frontend/src/components/ImageUpload.tsx#L39-L46
e349205f0734e37ffd496135038100ac551462dd
booking-microservices-nestjs
github_2023
meysamhadeli
typescript
Passenger.constructor
constructor(partial?: Partial<Passenger>) { Object.assign(this, partial); this.createdAt = partial?.createdAt ?? new Date(); }
// You can use 'Date | null' to allow null values
https://github.com/meysamhadeli/booking-microservices-nestjs/blob/a084c559f0c0e51a38f421a48bdaa2a549e5ed01/src/passenger/src/passenger/entities/passenger.entity.ts#L31-L34
a084c559f0c0e51a38f421a48bdaa2a549e5ed01
nodite-light
github_2023
nodite
typescript
authorized
const authorized = async (req: AuthorizedRequest, res: Response, next: NextFunction) => { const { authorization } = req.headers as unknown as { authorization?: string; }; if (!authorization) { return next(new AppError(httpStatus.UNAUTHORIZED, 'Missing authorization in request header')); } if (author...
/** * Authorized middleware. * @param req * @param res * @param next * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/packages/admin-auth/src/middlewares/authorized.middleware.ts#L84-L118
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
onlyStatus200
const onlyStatus200 = (req: Request, res: Response) => { if (req.headers['apicache-control'] === 'no-cache') return false; return res.statusCode === 200; };
// cache only HTTP response code 200 where apicache-control is not set to no-cache
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/packages/admin-core/src/middlewares/cache.middleware.ts#L7-L10
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
onlyWithUniqueBody
const onlyWithUniqueBody = (req: Request) => { if (req.method === 'POST' && req.body) { return md5(JSON.stringify(req.body)); } return req.path; };
// cache only POST requests with unique body
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/packages/admin-core/src/middlewares/cache.middleware.ts#L13-L18
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
errorHandling
const errorHandling = ( error: Error, req: Request, res: Response, // eslint-disable-next-line next: NextFunction, ) => { let wrappedError = error; // tsoa - validate error if (error instanceof ValidateError) { wrappedError = new AppError( httpStatus.BAD_REQUEST, lodash.mapValues(error....
// catch all unhandled errors
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/packages/admin-core/src/middlewares/errorHandling.middleware.ts#L12-L51
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
validate
const validate = (schema: ValidationSchema) => (req: Request, res: Response, next: NextFunction) => { /* eslint-disable */ const pickObjectKeysWithValue = (Object: object, Keys: string[]) => Keys.reduce((o, k) => ((o[k] = Object[k]), o), {}); /* eslint-enable */ const definedSchemaKeys = Object...
/* * Validate request according to the defined validation Schema (see `validations` directory) * The request's body, params or query properties may be checked only. * An operational AppError is thrown if data validation fails. * In case of success, go to the next middleware */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/packages/admin-core/src/middlewares/validate.middleware.ts#L14-L46
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
pickObjectKeysWithValue
const pickObjectKeysWithValue = (Object: object, Keys: string[]) => Keys.reduce((o, k) => ((o[k] = Object[k]), o), {});
/* eslint-disable */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/packages/admin-core/src/middlewares/validate.middleware.ts#L17-L18
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
Database.connect
static async connect(options: RedisStoreOptions): Promise<typeof Database.client> { try { Database.client = createClient({ ...options, socket: { reconnectStrategy: (retries) => { logger.warn(`Redis reconnecting ${retries}...`); return retries < 10 ? Math.min(r...
/** * Connect to the database * @param options * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/packages/admin-database/src/nodite-redis/index.ts#L25-L52
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
Database.disconnect
static async disconnect(): Promise<void> { await Database.client?.disconnect(); }
/** * Disconnect from the database */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/packages/admin-database/src/nodite-redis/index.ts#L57-L59
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
Database.subscribe
static subscribe(seeds?: Array<object>, seedsHandler?: SeedsHandler) { return (target: unknown) => { Database.models.push({ model: target as ModelCtor, seeds, seedsHandler, }); }; }
/** * Subscribe to the database * @param seeds * @param seedsHandler * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/packages/admin-database/src/nodite-sequelize/index.ts#L25-L33
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
Database.connect
static async connect(options: SequelizeStoreOptions): Promise<Sequelize | null> { const { host, port, user, pass, dbName } = options; // for sqlite engines let { engine = 'memory', storagePath = '' } = options; engine = engine.toLowerCase(); try { switch (engine) { case 'sqlite': ...
/** * Connect to the database * @param options * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/packages/admin-database/src/nodite-sequelize/index.ts#L40-L132
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
Database.disconnect
static async disconnect() { await Database.client?.close(); }
/** * Disconnect from the database */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/packages/admin-database/src/nodite-sequelize/index.ts#L137-L139
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
AuthService.register
public async register(body: RegisterBody): Promise<void> { const user = {} as IUser; user.username = body.username; user.email = body.email; user.password = body.password; await this.userService.create(user); }
/** * Register * @param body * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/auth/auth.service.ts#L25-L31
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
AuthService.login
public async login(body: LoginBody): Promise<LoginResponse> { let user: IUser | null = null; if (body.username) { user = await this.userService.getByUsername(body.username || ''); } else if (body.email) { user = await this.userService.getByEmail(body.email || ''); } if (lodash.isEmpty(...
/** * Login * @param body * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/auth/auth.service.ts#L38-L67
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
AuthService.logout
public async logout(user: AuthorizedRequest['user']): Promise<JwtDestroyType> { return jwtAsync().destroy(user?.jti || ''); }
/** * Logout * @param user * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/auth/auth.service.ts#L74-L76
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
CacheService.clearAllCache
public async clearAllCache(type: string, userId?: number): Promise<void> { if (['all', 'menu'].includes(type)) { this.clearMenuCache(userId); } if (['all', 'dict'].includes(type)) { this.clearDictCache(); } if (['all', 'locale'].includes(type)) { this.clearLocaleCache(); } ...
/** * Clear all cache. */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/cache/cache.service.ts#L20-L36
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
CacheService.clearPermsCache
public async clearPermsCache(userId?: number): Promise<void> { this.clearUserRoleCache(userId); if (userId) { const roles = await this.userService.selectRolesWithUser(userId); roles.forEach((role) => this.clearRolePermCache(role.roleId)); } else { this.clearRolePermCache(); } }
/** * Clear perms cache. * @param userId */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/cache/cache.service.ts#L69-L77
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
CasbinModel.enforcer
public static async enforcer(): Promise<Enforcer> { return casbin(); }
/** * Casbin enforcer. * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/casbin/casbin.model.ts#L23-L25
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
CasbinModel.removeRolePolicies
public static async removeRolePolicies( roleId: number, transaction?: Transaction, ): Promise<number> { return this.destroy({ where: { ptype: 'p', v0: `sys_role:${roleId}` }, transaction }); }
/** * Remove role policies. * @param roleId * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/casbin/casbin.model.ts#L32-L37
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
CasbinModel.addRolePolicies
public static async addRolePolicies( roleId: number, menuPerms: string[], transaction?: Transaction, ): Promise<CasbinRule[]> { return this.bulkCreate( menuPerms.map((perm) => { const parts = permToCasbinPolicy(perm); return { ptype: 'p', v0: `sys_role:${roleI...
/** * Add role policies. * @param roleId * @param menuPerms * @param transaction * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/casbin/casbin.model.ts#L46-L64
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
CasbinModel.assignRolesToUser
public static async assignRolesToUser( roleIds: number[], userId: number, transaction?: Transaction, ): Promise<CasbinModel[]> { return this.bulkCreate( roleIds.map((roleId) => ({ ptype: 'g', v0: `sys_user:${userId}`, v1: `sys_role:${roleId}` })), { transaction }, ); }
/** * Assign roles to user. * @param roleIds * @param userId * @param transaction * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/casbin/casbin.model.ts#L73-L82
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
CasbinModel.unassignRolesOfUser
public static async unassignRolesOfUser( roleIds: number[], userId: number, transaction?: Transaction, ): Promise<number> { const v1s = roleIds.map((roleId) => `sys_role:${roleId}`); return this.destroy({ where: { ptype: 'g', v0: `sys_user:${userId}`, v1: v1s }, transaction, }); ...
/** * Unassign roles of user. * @param roleIds * @param userId * @param transaction * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/casbin/casbin.model.ts#L91-L101
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictGroupService.selectDictGroupList
public async selectDictGroupList(): Promise<IDictGroup[]> { return lodash.map( await DictGroupModel.findAll({ order: [ ['orderNum', 'ASC'], ['groupId', 'ASC'], ], }), (m) => m.toJSON(), ); }
/** * Select dict group. * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_group.service.ts#L16-L26
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictGroupService.selectDictGroupTree
public async selectDictGroupTree(): Promise<DataTree<IDictGroup>[]> { return DataTreeUtil.buildTree(await this.selectDictGroupList(), { idKey: 'groupId', pidKey: 'parentId', }); }
/** * Select dict group tree. * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_group.service.ts#L32-L37
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictGroupService.selectDictGroupById
public async selectDictGroupById(id: string): Promise<IDictGroup> { const group = await DictGroupModel.findOne({ where: { groupId: id } }); if (!group) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Dict Group not found'); } return group.toJSON(); }
/** * Select dict group by id. * @param id * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_group.service.ts#L44-L50
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictGroupService.create
public async create(group: IDictGroupCreate): Promise<IDictGroup> { return DictGroupModel.create(group); }
/** * Create dict group. * @param group * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_group.service.ts#L57-L59
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictGroupService.update
public async update(id: string, body: IDictGroupUpdate): Promise<IDictGroup> { const preGroup = await DictGroupModel.findOne({ where: { groupId: id } }); if (!preGroup) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Dict Group not found'); } const group = await preGroup.update(body); r...
/** * Update dict group. * @param id * @param body * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_group.service.ts#L67-L74
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictGroupService.delete
public async delete(id: string): Promise<void> { const group = await DictGroupModel.findOne({ where: { groupId: id } }); if (!group) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Dict Group not found'); } await group.destroy(); }
/** * Delete dict group. * @param id */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_group.service.ts#L80-L86
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictItemService.selectDictItemList
public async selectDictItemList(params?: QueryParams): Promise<SequelizePagination<IDictItem>> { return DictItemModel.paginate({ where: DictItemModel.buildQueryWhere(params), ...lodash.pick(params, ['itemsPerPage', 'page']), order: [ ['orderNum', 'ASC'], ['itemId', 'ASC'], ],...
/** * Select dict items. * @param dictType * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_item.service.ts#L19-L28
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictItemService.selectDictItemById
public async selectDictItemById(id: number): Promise<IDictItem> { const dictItem = await DictItemModel.findOne({ where: { itemId: id } }); if (!dictItem) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Dict Item not found'); } return dictItem.toJSON(); }
/** * Select dict item by id. * @param id * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_item.service.ts#L35-L41
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictItemService.create
public async create(dictItem: IDictItemCreate): Promise<IDictItem> { return DictItemModel.create(dictItem); }
/** * Create dict item. * @param dictItem * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_item.service.ts#L48-L50
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictItemService.update
public async update(id: number, body: IDictItemUpdate): Promise<IDictItem> { const preDictItem = await DictItemModel.findOne({ where: { itemId: id } }); if (!preDictItem) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Dict Item not found'); } const dictItem = await preDictItem.update(body)...
/** * Update dict item. * @param id * @param body * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_item.service.ts#L58-L65
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictItemService.delete
public async delete(id: number): Promise<void> { const dictItem = await DictItemModel.findOne({ where: { itemId: id } }); if (!dictItem) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Dict Item not found'); } await dictItem.destroy(); }
/** * Delete dict item. * @param id */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_item.service.ts#L71-L77
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictTypeService.selectDictTypeList
public async selectDictTypeList( params?: QueryParams, ): Promise<SequelizePagination<IDictTypeWithItems>> { const page = await DictTypeModel.paginate({ where: DictTypeModel.buildQueryWhere(params), ...lodash.pick(params, ['itemsPerPage', 'page']), order: [ ['orderNum', 'ASC'], ...
/** * Search dict types. * @param params * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_type.service.ts#L21-L48
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictTypeService.selectDictTypeById
public async selectDictTypeById(id: string): Promise<IDictTypeWithItems> { const dictType = await DictTypeModel.findOne({ where: { [Op.or]: { dictId: id, dictKey: id } }, include: [ { model: DictItemModel, required: false, order: [ ['orderNum', 'ASC'], ...
/** * Select dict type by id. * @param id * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_type.service.ts#L55-L73
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictTypeService.create
public async create(dictType: IDictTypeCreate): Promise<IDictType> { return DictTypeModel.create(dictType); }
/** * Create dict type. * @param dictType * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_type.service.ts#L80-L82
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictTypeService.update
public async update(id: string, body: IDictTypeUpdate): Promise<IDictType> { const preDictType = await DictTypeModel.findOne({ where: { [Op.or]: { dictId: id, dictKey: id } }, }); if (!preDictType) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Dict Type not found'); } const dict...
/** * Update dict type. * @param id * @param body * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_type.service.ts#L90-L99
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
DictTypeService.delete
public async delete(id: string): Promise<void> { const dictType = await DictTypeModel.findOne({ where: { [Op.or]: { dictId: id, dictKey: id } }, }); if (!dictType) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Dict Type not found'); } await dictType.destroy(); }
/** * Delete dict type. * @param id */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/dict/dict_type.service.ts#L105-L113
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
LocaleService.selectLocaleList
public async selectLocaleList(): Promise<ILocale[]> { const locales = await LocaleModel.findAll({ order: [ ['orderNum', 'ASC'], ['localeId', 'ASC'], ], }); return locales.map((i) => i.toJSON()); }
/** * Select locales. * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/locale/locale.service.ts#L31-L40
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
LocaleService.selectAvailableLocaleList
public async selectAvailableLocaleList(): Promise<IAvailableLocale[]> { const locales = await LocaleModel.scope('available').findAll({ attributes: ['langcode', 'momentCode', 'icon', 'label', 'isDefault'], order: [ ['orderNum', 'ASC'], ['localeId', 'ASC'], ], }); return loc...
/** * Select available locales. * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/locale/locale.service.ts#L46-L56
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
LocaleService.selectLocaleById
public async selectLocaleById(id: number): Promise<ILocale> { const locale = await LocaleModel.findOne({ where: { localeId: id } }); if (!locale) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Locale not found'); } return locale.toJSON(); }
/** * Select locale by id. * @param id * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/locale/locale.service.ts#L63-L69
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
LocaleService.createLocale
public async createLocale(locale: ILocaleCreate): Promise<ILocale> { return LocaleModel.create(locale); }
/** * Create. * @param locale * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/locale/locale.service.ts#L76-L78
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
LocaleService.updateLocale
public async updateLocale(id: number, locale: ILocaleUpdate): Promise<ILocale> { // status. if ( !lodash.isUndefined(locale.status) && !lodash.isNull(locale.status) && !locale.status && (await LocaleModel.count({ where: { status: 1, localeId: { [Op.ne]: id } } })) === 0 ) { thr...
/** * Update. * @param id * @param locale * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/locale/locale.service.ts#L86-L116
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
LocaleService.deleteLocale
public async deleteLocale(id: number): Promise<void> { const locale = await LocaleModel.findOne({ where: { localeId: id } }); if (!locale) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Locale not found'); } await locale.destroy(); }
/** * Delete. * @param id */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/locale/locale.service.ts#L122-L128
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
LocaleService.selectAvailableMessageList
public async selectAvailableMessageList(langcode: string): Promise<IAvailableMessage[]> { const messages = await LocaleMessageModel.scope('available').findAll({ attributes: ['langcode', 'message'], where: { langcode }, include: [{ model: LocaleSourceModel, attributes: ['source', 'context'] }], ...
/** * Select available messages. * @param langcode * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/locale/locale.service.ts#L135-L148
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
LocaleService.selectSourceList
public async selectSourceList( langcode: string, params?: QueryParams, ): Promise<SequelizePagination<ISourceWithMessages>> { const page = await LocaleSourceModel.paginate({ where: LocaleSourceModel.buildQueryWhere(params), ...lodash.pick(params, ['itemsPerPage', 'page']), include: [ ...
/** * Select source list. * @param langcode * @param params * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/locale/locale.service.ts#L156-L175
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
LocaleService.createSourceIfMissing
public async createSourceIfMissing(body: ISourceCreate): Promise<ILocaleSource> { let source = await LocaleSourceModel.findOne({ where: { source: body.source, context: body.context }, }); if (lodash.isEmpty(source)) { source = await LocaleSourceModel.create(lodash.omit(body, 'locations')); ...
/** * Create source if missing. * @param body * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/locale/locale.service.ts#L182-L211
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
LocaleService.upsertMessages
public async upsertMessages(messages: IMessageUpsert[]): Promise<void> { await LocaleMessageModel.bulkCreate(messages, { updateOnDuplicate: ['message', 'customized'], }); }
/** * Upsert messages. * @param messages */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/locale/locale.service.ts#L217-L221
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
initialSeeds
async function initialSeeds(model: typeof MenuModel, seeds: DataTree<IMenu>[] = [], parentId = '') { lodash.forEach(seeds, async (seed, idx) => { const menu = await model.create({ ...seed, parentId, orderNum: idx, }); if (lodash.isEmpty(seed.children)) return; await initialSeeds(mo...
/** * Seeds handler. * @param model * @param seeds * @param parentId */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/menu/menu.model.ts#L29-L41
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
MenuModel.findAllByUserId
public static findAllByUserId( userId?: number, options?: FindOptions<Attributes<MenuModel>>, ): Promise<MenuModel[]> { if (!userId) return Promise.resolve([]); // TODO: user permission return this.findAll<MenuModel>(options); }
/** * findAllByUserId. * @param userId * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/menu/menu.model.ts#L125-L132
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
MenuService.selectMenuList
public async selectMenuList(userId?: number): Promise<IMenu[]> { let menus: MenuModel[] = []; // admin. if (await this.userService.isAdmin(userId)) { menus = lodash.map(await MenuModel.findAll(), (m) => m.toJSON()); } // no-admin user. else { // user. const user = await UserMo...
/** * Select menu list. * @param userId * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/menu/menu.service.ts#L26-L68
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
MenuService.selectMenuTree
public async selectMenuTree(userId?: number): Promise<DataTree<IMenu>[]> { return DataTreeUtil.buildTree(await this.selectMenuList(userId), { idKey: 'menuId', pidKey: 'parentId', }); }
/** * Select menu tree. * @param userId * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/menu/menu.service.ts#L75-L80
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
MenuService.selectMenuById
public async selectMenuById(id: string): Promise<IMenu> { const menu = await MenuModel.findOne({ where: { menuId: id } }); if (!menu) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Menu not found'); } return menu.toJSON(); }
/** * Select menu by id. * @param id * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/menu/menu.service.ts#L87-L93
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
MenuService.create
public async create(menu: IMenuCreate): Promise<IMenu> { return MenuModel.create(menu); }
/** * create * @param menu * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/menu/menu.service.ts#L100-L102
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
MenuService.update
public async update(id: string, body: IMenuUpdate): Promise<IMenu> { const preMenu = await MenuModel.findOne({ where: { menuId: id } }); if (!preMenu) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Menu not found'); } const menu = await preMenu.update(body); return menu.toJSON(); }
/** * Update menu. * @param id * @param body * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/menu/menu.service.ts#L110-L117
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
MenuService.delete
public async delete(id: string): Promise<void> { const menu = await MenuModel.findOne({ where: { menuId: id } }); if (!menu) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Menu not found'); } if (menu.getDataValue('deleted') === 9) { throw new AppError(httpStatus.UNPROCESSABLE_ENTI...
/** * Delete menu. * @param id */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/menu/menu.service.ts#L123-L135
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
RoleService.selectRoleList
public async selectRoleList(params?: QueryParams): Promise<SequelizePagination<IRole>> { const page = await RoleModel.paginate({ attributes: ['roleId', 'roleName', 'roleKey', 'orderNum', 'status', 'createTime'], where: RoleModel.buildQueryWhere(params), ...lodash.pick(params, ['itemsPerPage', 'pag...
/** * Search roles. * @param params * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/role/role.service.ts#L25-L40
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
RoleService.selectRoleById
public async selectRoleById(id: number): Promise<IRole> { const role = await RoleModel.findOne({ where: { roleId: id } }); if (!role) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Role not found'); } return role.toJSON(); }
/** * Select role by id. * @param id * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/role/role.service.ts#L47-L53
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
RoleService.create
public async create(role: IRoleCreate): Promise<IRole> { return RoleModel.create(role); }
/** * Create role. * @param role * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/role/role.service.ts#L60-L62
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
RoleService.update
public async update(id: number, body: IRoleUpdate): Promise<IRole> { const preRole = await RoleModel.findOne({ where: { roleId: id } }); if (!preRole) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Role not found'); } const role = await preRole.update(body); return role.toJSON(); }
/** * Update role. * @param body * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/role/role.service.ts#L69-L76
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec
nodite-light
github_2023
nodite
typescript
RoleService.delete
public async delete(id: number): Promise<void> { if (id === 1) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Admin role is not allow delete!'); } if (await RoleUserModel.findOne({ where: { roleId: id } })) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Role is using, please una...
/** * Delete role. * @param id * @returns */
https://github.com/nodite/nodite-light/blob/f8827d69f0c67e7c59042fd0f3e246a67e80e0ec/services/admin-api/src/components/role/role.service.ts#L83-L103
f8827d69f0c67e7c59042fd0f3e246a67e80e0ec