0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-02-03 21:48:55 -05:00
logto/packages/schemas/src/gen/utils.ts

121 lines
2.7 KiB
TypeScript

import { Optional } from '@logto/essentials';
export const normalizeWhitespaces = (string: string): string => string.replace(/\s+/g, ' ').trim();
const getCountDelta = (value: string): number => {
if (value === '(') {
return 1;
}
if (value === ')') {
return -1;
}
return 0;
};
export const removeParentheses = (value: string) =>
Object.values(value).reduce<{ result: string; count: number }>(
(previous, current) => {
const count = previous.count + getCountDelta(current);
return count === 0 && current !== ')'
? { result: previous.result + current, count }
: { result: previous.result, count };
},
{
result: '',
count: 0,
}
).result;
export type ParenthesesMatch = { body: string; prefix: string };
export const findFirstParentheses = (value: string): Optional<ParenthesesMatch> => {
const { matched, count, ...rest } = Object.values(value).reduce<{
body: string;
prefix: string;
count: number;
matched: boolean;
}>(
(previous, current) => {
const count = previous.count + getCountDelta(current);
if (count === 0) {
if (current === ')') {
return {
...previous,
count,
matched: true,
};
}
return {
...previous,
count,
prefix: previous.prefix + current,
};
}
return {
...previous,
count,
body: previous.body + (count === 1 && current === '(' ? '' : current),
};
},
{
body: '',
prefix: '',
count: 0,
matched: false,
}
);
return matched ? rest : undefined;
};
const getRawType = (value: string): string => {
const bracketIndex = value.indexOf('[');
return bracketIndex === -1 ? value : value.slice(0, bracketIndex);
};
// Reference: https://github.com/SweetIQ/schemats/blob/7c3d3e16b5d507b4d9bd246794e7463b05d20e75/src/schemaPostgres.ts
// eslint-disable-next-line complexity
export const getType = (
value: string
): 'string' | 'number' | 'boolean' | 'Record<string, unknown>' | 'Date' | undefined => {
switch (getRawType(value)) {
case 'bpchar':
case 'char':
case 'varchar':
case 'text':
case 'citext':
case 'uuid':
case 'bytea':
case 'inet':
case 'time':
case 'timetz':
case 'interval':
case 'name':
return 'string';
case 'int2':
case 'int4':
case 'int8':
case 'bigint':
case 'float4':
case 'float8':
case 'numeric':
case 'money':
case 'oid':
return 'number';
case 'bool':
return 'boolean';
case 'json':
case 'jsonb':
return 'Record<string, unknown>';
case 'date':
case 'timestamp':
case 'timestamptz':
return 'Date';
default:
}
};