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 requests. return new Response(null, { headers: { ...corsHeaders, "access-control-allow-headers": request.headers.get( "Access-Control-Request-Headers", )!, }, }); } else { // Handle standard OPTIONS request. return new Response(null, { headers: { Allow: "GET, HEAD, POST, OPTIONS", }, }); } }
// 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 defined recording rules. * They should not be used by exporters or direct instrumentation. * * OpenTelemetry metric names are already validated in the Meter when they are created, * and they match the format `[a-zA-Z][a-zA-Z0-9_.\-]*` which is very close to a valid * prometheus metric name, so we only need to strip characters valid in OpenTelemetry * but not valid in prometheus and replace them with '_'. * * @param name name to be sanitized */
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}'. Must be one of ${headerTypes.join( ", ", )}`, ); } return (header || headerTypes[0]) as (typeof headerTypes)[number]; }
// --------------------------------------------------
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(path.join(cwd, 'deno.json')) || fs.existsSync(path.join(cwd, 'deno.lock')) ) { return 'deno' } if (fs.existsSync(path.join(cwd, 'pnpm-lock.yaml'))) { return 'pnpm' } return null }
// 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): 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.startsWith('__') } // Loop over each type in the schema and remove any reserved fields. for (const type of this.schema.types) { type.fields = type.fields.filter(field => { if (isReserved(field.name)) { // console.warn( // `\x1b[33mWarning: forbidden field "${field.name}" detected in type "${type.name}". This field will be excluded from the schema.\x1b[0m` // ) return false } return true }) } // Loop over each input in the schema and remove any reserved fields. for (const input of this.schema.inputs) { input.fields = input.fields.filter(field => { if (isReserved(field.name)) { // console.warn( // `\x1b[33mWarning: reserved field "${field.name}" detected in input "${input.name}". This field will be excluded from the schema.\x1b[0m` // ) return false } return true }) } }
/** * 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.startsWith('__') }
// 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() if (!ctx) { consola.warn( 'Context is not defined. Make sure AsyncLocalStorage is supported in your environment.' ) } ctx?.set("graphqlResolveInfo", info) const auth = ctx?.get('auth') if (auth?.active) { scope.setUser({ id: auth.sub, username: auth.preferred_username, email: auth.email, details: auth }) } // get query or mutation field let type: Maybe<GraphQLObjectType> | null = null switch (info.operation.operation) { case 'query': type = info.schema.getQueryType() break case 'mutation': type = info.schema.getMutationType() break case 'subscription': type = info.schema.getSubscriptionType() break default: throw new Error('Unknown operation') } const field = type?.getFields()[info.fieldName] // Get the list of arguments expected by the current query field. const fieldArguments = field?.args || [] // Prepare the arguments for the resolver function call by adding any missing arguments with an undefined value. const preparedArguments = fieldArguments.reduce( (acc: {[x: string]: undefined}, arg: {name: string | number}) => { if (args[arg.name] !== undefined) { acc[arg.name] = args[arg.name] } else { acc[arg.name] = undefined } return acc }, {} as Record<string, any> ) // Determine the resolver function to call (either the given function or the wrappedWithContext function if it exists). let inner = await fn let baseSelectionSet: SelectionSetNode['selections'] = [] // Find the selection set for the current field. for (const selection of info.operation.selectionSet.selections) { if ( selection.kind === 'Field' && selection.name.value === info.fieldName ) { baseSelectionSet = selection.selectionSet?.selections || [] } } // Wrap the resolver function with any required middleware. const wrappedFn = await wrapFunctionsRecursively( inner, spreadFunctionArguments, this, baseSelectionSet, info ) // Call the resolver function with the prepared arguments. if (typeof wrappedFn !== 'function') { return wrappedFn } const res = await wrappedFn(preparedArguments) return res }) }
// 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 (program[label.text]![read.text]) { throw new Error( `Duplicate instruction for: ${label.text} | ${read.text}`, ); } for (let i = 0; i < instructions.length; i++) { const instruction = instructions[i]; instruction.id = `${id++}`; instruction.branch = branch; instruction.index = i; } program[label.text]![read.text] = { index, instructions, }; } return program; }
// 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 actualRouteName - The expected route name that should have been used. */
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 = getParamName(value) const isNotParam = !paramName if (isNotParam) { continue } const isOptional = isOptionalParamSyntax(value) const paramKey = isOptional ? `?${paramName}` : paramName const valueOnUrl = actualSearch.get(key) ?? undefined const paramValue = getParamValue(valueOnUrl, query.params[paramKey], isOptional) values[paramName] = paramValue } return values }
/** * 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, ZodPromise, ZodFunction, } = await import('zod') return { ZodSchema, ZodString, ZodBoolean, ZodDate, ZodNumber, ZodLiteral, ZodObject, ZodEnum, ZodNativeEnum, ZodArray, ZodTuple, ZodUnion, ZodDiscriminatedUnion, ZodRecord, ZodMap, ZodSet, ZodIntersection, ZodPromise, ZodFunction, } }
// 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 = parsedData.summary const is_waiting = (agent != "simple"); if (!is_internal) this._chatHistory.push({ agent: 'RepoPilot', message: response}); else if (agent == "navigator") { this._internalHistoryNav.push({agent: agent, message: response, summary: _summary}) } else if (agent == "editor") { this._internalHistoryEdit.push({agent: agent, message: response, summary: _summary}) } this._latestMessage = response; if (this._view && this._view.visible) { if (!is_waiting) this._view.webview.postMessage({ type: 'updateChatHistory', value: this._chatHistory }); else { this._view.webview.postMessage({ type: 'updateChatHistoryW', value: this._chatHistory }); } this._view.webview.postMessage({ type: 'updateInternalHistoryNav', value: this._internalHistoryNav}); this._view.webview.postMessage({ type: 'updateInternalHistoryEdit', value: this._internalHistoryEdit}) } } }
// 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 (authorization?.indexOf('Bearer ') === -1) { return next(new AppError(httpStatus.UNAUTHORIZED, 'Invalid authorization format')); } const [, token] = (authorization as string).split(' '); try { const decoded = (await jwtAsync().verify( token, config.jwtSecret.trim(), )) as AuthorizedRequest['user'] & JwtPayload; req.user = decoded; httpContext.set('user', decoded); } catch (err) { if (err instanceof TokenInvalidError) { err.message = 'Invalid authorization'; } else if (err instanceof TokenDestroyedError) { err.message = 'Authorization expired'; } return next(new AppError(httpStatus.UNAUTHORIZED, (err as Error).message)); } return next(); };
/** * 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.fields, (f) => f.message).toString(), ); } else if (error instanceof SequelizeValidationError) { wrappedError = new AppError( httpStatus.UNPROCESSABLE_ENTITY, `${error.message}: ${lodash.map(error.errors, 'message').toString()}`, ); } errorHandler.handleError(wrappedError); const isTrusted = errorHandler.isTrustedError(wrappedError); const httpStatusCode = isTrusted ? (wrappedError as AppError).httpCode : httpStatus.INTERNAL_SERVER_ERROR; const responseError = isTrusted ? wrappedError.message : httpStatus[httpStatus.INTERNAL_SERVER_ERROR]; res.status(httpStatusCode).json({ error: true, httpCode: httpStatusCode, message: responseError, } as IResponse<unknown>); };
// 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.keys(schema); const acceptableSchemaKeys: string[] = ['params', 'query', 'body']; const filterOutNotValidSchemaKeys: string[] = Object.keys(schema).filter((k) => acceptableSchemaKeys.includes(k), ); if (filterOutNotValidSchemaKeys.length !== definedSchemaKeys.length) { const e = `Wrongly defined validation Schema keys: [${definedSchemaKeys}], allowed keys: [${acceptableSchemaKeys}]`; throw new AppError(httpStatus.INTERNAL_SERVER_ERROR, e, false); } const validSchema = pickObjectKeysWithValue(schema, filterOutNotValidSchemaKeys); const object = pickObjectKeysWithValue(req, Object.keys(validSchema)); const { value, error } = Joi.compile(validSchema) .prefs({ errors: { label: 'key' } }) .validate(object); if (error) { const errorMessage = error.details.map((details) => details.message).join(', '); return next(new AppError(httpStatus.BAD_REQUEST, errorMessage)); } Object.assign(req, value); return next(); };
/* * 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(retries * 50, 500) : false; }, }, }).on('error', () => {}); await Database.client.connect(); logger.info('Redis connected'); } catch (err) { logger.error('Redis connection error, some features are not be available', err); Database.client = null; } // set cache manager adapter if (Database.client) { cacheManger.setClient(useAdapter(Database.client as never)); logger.info('Redis cache manager adapter set'); } return Database.client; }
/** * 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': storagePath = storagePath.trim(); if (storagePath.length === 0) { throw new Error('The "storagePath" must be specified when using the "sqlite" engine'); } Database.client = new Sequelize({ dialect: 'sqlite', storage: `${storagePath}/${dbName}.sqlite`, define: { charset: 'utf8', collate: 'utf8_general_ci', }, logging: (sql: string) => logger.debug(sql), }); break; case 'mariadb': case 'mssql': case 'mysql': case 'postgres': Database.client = new Sequelize({ host, port, database: dbName, dialect: engine, username: user, password: pass, define: { charset: 'utf8', collate: 'utf8_general_ci', }, logging: (sql: string) => logger.debug(sql), }); break; case 'memory': default: engine = 'in:memory'; Database.client = new Sequelize('sqlite::memory:', { define: { charset: 'utf8', collate: 'utf8_general_ci', }, logging: (sql: string) => logger.debug(sql), }); break; } await Database.client.authenticate(); logger.info(`Successfully connected to "${engine}" database server`); Database.client.addModels(lodash.map(Database.models, 'model')); await Database.client.sync(); logger.info('Successfully synced models'); await Promise.all( lodash.map(Database.models, async (meta) => { if (!meta.seeds) return; logger.debug(`found model seed: ${meta.model.getTableName()}`); if (await meta.model.findOne()) return; if (!meta.seedsHandler) { await meta.model.bulkCreate(meta.seeds as never[]); } else { await meta.seedsHandler(meta.model, meta.seeds); } }), ); logger.info('Successfully loaded models'); } catch (err) { logger.error(`Failed to connect to ${engine} server: ${err}`); exit(1); } return Database.client; }
/** * 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(user)) { throw new AppError(httpStatus.BAD_REQUEST, 'Invalid username or email.'); } // valid password. this.userService.validPassword(body.password, user.password); // generate jwt token. const payload: AuthorizedRequest['user'] = { userId: user.userId, username: user.username, email: user.email, }; return { token: await jwtAsync().sign(payload as object, config.jwtSecret, { expiresIn: config.jwtExpiresIn, }), expiresIn: config.jwtExpiresIn, }; }
/** * 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(); } if (['all', 'perms'].includes(type)) { await this.clearPermsCache(userId); } }
/** * 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:${roleId}`, v1: parts[0], v2: parts[1], v3: parts[2], }; }), { transaction }, ); }
/** * 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); return group.toJSON(); }
/** * 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); return dictItem.toJSON(); }
/** * 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'], ['dictId', 'ASC'], ], include: [ { model: DictItemModel, required: false, attributes: ['itemId'], order: [ ['orderNum', 'ASC'], ['itemId', 'ASC'], ], }, ], }); return { ...page, items: page.items.map((i) => i.toJSON()), }; }
/** * 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'], ['itemId', 'ASC'], ], }, ], }); if (!dictType) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Dict Type not found'); } return dictType.toJSON(); }
/** * 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 dictType = await preDictType.update(body); return dictType.toJSON(); }
/** * 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 locales.map((i) => i.toJSON()); }
/** * 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 ) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'At least one locale must be enable.'); } // isDefault. if (lodash.isUndefined(locale.isDefault) || lodash.isNull(locale.isDefault)) { /** empty */ } // If isDefault is true, set all other locales to false. else if (locale.isDefault) { await LocaleModel.update({ isDefault: 0 }, { where: { isDefault: 1 } }); } // If isDefault is false, check if there is at least one default locale. else { const count = await LocaleModel.count({ where: { isDefault: 1, localeId: { [Op.ne]: id } } }); if (count === 0) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'At least one locale must be default.'); } } await LocaleModel.update(locale, { where: { localeId: id } }); return LocaleModel.findOne({ where: { localeId: id } }); }
/** * 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'] }], }); return lodash.map(messages, (i) => ({ langcode: i.langcode, message: i.message, source: i.source?.source, context: i.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: [ { model: LocaleMessageModel, where: { langcode }, required: false, }, ], }); return { ...page, items: page.items.map((i) => i.toJSON()), }; }
/** * 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')); await LocaleLocationModel.bulkCreate( lodash.map(body.locations, (location) => lodash.set(location, 'srcId', source.getDataValue('srcId')), ), ); const defaultLocale = await LocaleModel.findOne({ attributes: ['langcode'], where: { isDefault: 1 }, }); await this.upsertMessages([ { srcId: source.getDataValue('srcId'), langcode: defaultLocale.getDataValue('langcode'), message: body.source, }, ] as IMessageUpsert[]); } return source.toJSON(); }
/** * 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(model, seed.children, menu.getDataValue('menuId')); }); }
/** * 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 UserModel.findOne({ where: { userId }, include: [ { model: RoleModel, attributes: ['roleId'], required: false, include: [ { model: MenuModel, required: false, }, ], }, ], }); if (!user) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'User not found'); } menus = lodash .chain(user.roles) .map('menus') .flatten() .map((m) => m.toJSON()) .uniqBy('menuId') .value(); } // order return lodash.orderBy(menus, ['orderNum', 'menuId'], ['asc', 'asc']); }
/** * 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_ENTITY, 'Menu is not allow delete!'); } return menu.destroy(); }
/** * 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', 'page']), order: [ ['orderNum', 'ASC'], ['roleId', 'ASC'], ], }); return { ...page, items: page.items.map((i) => i.toJSON()), }; }
/** * 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 unassign first!'); } const role = await RoleModel.findOne({ where: { roleId: id } }); if (!role) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Role was not found!'); } if (role.getDataValue('deleted') === 9) { throw new AppError(httpStatus.UNPROCESSABLE_ENTITY, 'Role is not allow delete!'); } return role.destroy(); }
/** * 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