ramda#reject TypeScript Examples
The following examples show how to use
ramda#reject.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts From reskript with MIT License | 6 votes |
runBuild = (configuration: Configuration[]): Promise<Stats> => {
const executor = (resolve: (value: Stats) => void) => webpack(
configuration as Configuration, // https://github.com/Microsoft/TypeScript/issues/14107
(err?: Error, stats?: Stats) => {
if (err) {
logger.error(err.toString());
process.exit(22);
}
if (!stats) {
logger.error('Unknown error: webpack does not return its build stats');
process.exit(22);
}
const toJsonOptions = {all: false, errors: true, warnings: true, assets: true};
// webpack的`toJson`的定义是错的
const {errors, warnings} = stats.toJson(toJsonOptions);
for (const error of reject(isNil, errors ?? [])) {
printWebpackResult('error', error as unknown as WebpackResult);
}
for (const warning of reject(isNil, warnings ?? [])) {
printWebpackResult('warn', warning as unknown as WebpackResult);
}
if (stats.hasErrors()) {
process.exit(22);
}
resolve(stats);
}
);
return new Promise(executor);
}
Example #2
Source File: index.ts From reskript with MIT License | 6 votes |
toConfiguration = async (cmd: BuildCommandLineArgs, buildContext: BuildContext) => {
const extras = [
cmd.analyze && partials.analyze(buildContext),
cmd.profile && partials.profile(),
!cmd.sourceMaps && partials.noSourceMaps(),
];
return createWebpackConfig(
buildContext,
{
strict: {
disableRequireExtension: cmd.strict,
caseSensitiveModuleSource: cmd.strict,
typeCheck: cmd.strict,
},
extras: reject((v: false | Configuration): v is false => !v, extras),
}
);
}
Example #3
Source File: case.ts From reskript with MIT License | 6 votes |
parseMarkdownToCases = async (markdown: string): Promise<PlayCase[]> => {
if (!markdown) {
return [];
}
const nodes = splitToCaseNodes(markdown);
const cases = await pMap(nodes, parseToCase);
return reject(isNil, cases);
}
Example #4
Source File: tenant.controller.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@Patch('/:tenantUuid')
@Permissions('settings/update')
@AuditLog('settings/update')
@ApiOkResponse({ type: Tenant })
public async patch(@Body() updatedTenant: any): Promise<Tenant> {
const existingTenant = await this.tenantService.findOne();
return this.tenantService.update(existingTenant.uuid, omit(['users', 'features'])({
...existingTenant,
...updatedTenant,
settings: {
...existingTenant.settings,
...reject(equals('hidden'))({
...updatedTenant.settings,
something: "hidden"
})
},
updatedAt: new Date(),
}) as any);
}
Example #5
Source File: useBookmark.ts From back-home-safe with GNU General Public License v3.0 | 5 votes |
[UseBookmarkLocationProvider, useBookmarkLocation] = constate(
() => {
const { currentTime } = useTime();
const {
value: { savedLocations },
setValue,
} = useData();
const removeBookmarkLocation = useCallback(
(id: string) => {
setValue((prev) => ({
...prev,
savedLocations: reject(
({ id: itemId }) => itemId === id,
prev.savedLocations
),
}));
},
[setValue]
);
const createBookmarkLocation = useCallback(
(record: Omit<SavedLocation, "createdAt">) => {
setValue((prev) => ({
...prev,
savedLocations: [
{
...trimData(record),
createdAt: currentTime.toISOString(),
id: uuid(),
},
...prev.savedLocations,
],
}));
},
[setValue, currentTime]
);
const getBookmarkLocationId = useCallback(
(record: Omit<SavedLocation, "createdAt">) => {
const trimmedData = trimData(record);
const result = find((item) => {
const trimmedItem = trimData(item);
return equals(trimmedData, trimmedItem);
}, savedLocations);
if (!result) return null;
return result.id;
},
[savedLocations]
);
return {
bookmarkLocation: savedLocations,
removeBookmarkLocation,
createBookmarkLocation,
getBookmarkLocationId,
};
}
)
Example #6
Source File: duplicatePackages.ts From reskript with MIT License | 5 votes |
extractUniqueModules = (compilations: StatsCompilation[]): string[] => {
const modules = compilations.flatMap(c => c.modules);
const names = modules.map(m => m?.nameForCondition);
return uniq(reject(isNil, names));
}
Example #7
Source File: htmlImportable.ts From reskript with MIT License | 5 votes |
extractScriptEntries = (compilations: StatsCompilation[]): string[] => {
const entries = compilations.flatMap(c => Object.values(c.entrypoints ?? {}));
// 这里的`assets`是有顺序的(大概),被别人依赖的在前面(大概),真正的入口是最后一个(大概)
return uniq(reject(isNil, entries.map(v => last(v.assets ?? [])?.name)));
}
Example #8
Source File: config.ts From reskript with MIT License | 5 votes |
createWebpackConfig = async (target: string, cmd: PlayCommandLineArgs, buildContext: BuildContext) => {
const hostType = await resolveDevHost(cmd.host);
const extra = await createWebpackDevServerPartial(buildContext, hostType);
const baseConfig = await createBaseWebpackConfig(buildContext, {extras: [extra]});
const enableConcurrentMode = cmd.concurrentMode ?? buildContext.projectSettings.play.defaultEnableConcurrentMode;
const playEntryPath = resolveEntryPath(enableConcurrentMode);
const componentTypeName = resolveComponentName(target);
const entryLoaders = [
await loaders.babel(buildContext),
{
loader: await resolve('loader-of-loader'),
options: {
resolveLoader: async () => {
return {
loader: path.join(currentDirectory, 'loader.js'),
type: 'module',
options: {
componentTypeName,
cwd: buildContext.cwd,
componentModulePath: path.resolve(buildContext.cwd, target),
globalSetupModulePath: cmd.setup
? path.resolve(cmd.cwd, cmd.setup)
: buildContext.projectSettings.play.defaultGlobalSetup,
},
};
},
},
},
];
const config: webpack.Configuration = {
...baseConfig,
entry: {
index: playEntryPath,
},
module: {
rules: [
{
test: playEntryPath,
use: reject(isNil, entryLoaders),
},
...(baseConfig.module?.rules ?? []),
],
},
resolve: {
...baseConfig.resolve,
fallback: {
...baseConfig.resolve?.fallback,
// React要从`17.0.3`开始才会有`exports`配置,这之前的版本在ESM下是必须加`.js`后续的。
// 利用这个`resolve.fallback`,可以在找不到`react/jsx-runtime`时跳到`react/jsx-runtime.js`上去,兼容旧版本。
'react/jsx-runtime': 'react/jsx-runtime.js',
},
},
};
return config;
}
Example #9
Source File: useTravelRecord.ts From back-home-safe with GNU General Public License v3.0 | 4 votes |
[UseTravelRecordProvider, useTravelRecord] = constate(() => {
const { currentTime } = useTime();
const {
value: { travelRecords },
setValue,
} = useData();
const browserHistory = useHistory();
const [autoRemoveRecordDay, setAutoRemoveRecordDay] = useLocalStorage(
"auto_remove_record_after",
30
);
const { pastTravelRecord, currentTravelRecord } = useMemo(() => {
const { pastTravelRecord, currentTravelRecord } = travelRecords.reduce<{
pastTravelRecord: TravelRecord[];
currentTravelRecord: TravelRecord[];
}>(
(acc, item) => {
const isPast =
item.outTime && dayjs(item.outTime).isBefore(currentTime);
return isPast
? {
pastTravelRecord: [item, ...acc.pastTravelRecord],
currentTravelRecord: [...acc.currentTravelRecord],
}
: {
pastTravelRecord: [...acc.pastTravelRecord],
currentTravelRecord: [item, ...acc.currentTravelRecord],
};
},
{
pastTravelRecord: [],
currentTravelRecord: [],
}
);
return {
pastTravelRecord: sortRecord(pastTravelRecord),
currentTravelRecord: sortRecord(currentTravelRecord),
};
}, [travelRecords, currentTime]);
useEffect(() => {
setValue((prev) => ({
...prev,
travelRecords: prev.travelRecords.filter(
({ inTime }) =>
currentTime.diff(inTime, "day") <= (autoRemoveRecordDay || 30)
),
}));
}, [currentTime, setValue, autoRemoveRecordDay]);
const createTravelRecord = useCallback(
(record: TravelRecord) => {
setValue((prev) => ({
...prev,
travelRecords: [record, ...prev.travelRecords],
}));
},
[setValue]
);
const getTravelRecord = useCallback(
(id: string) => find(({ id: itemId }) => itemId === id, travelRecords),
[travelRecords]
);
const updateTravelRecord = useCallback(
(id: string, data: Partial<TravelRecord>) => {
setValue((prev) => {
const index = findIndex(
({ id: itemId }) => itemId === id,
prev.travelRecords
);
if (index < 0) return prev;
return {
...prev,
travelRecords: adjust(
index,
(currentRecord) => ({ ...currentRecord, ...data }),
prev.travelRecords
),
};
});
},
[setValue]
);
const removeTravelRecord = useCallback(
(id: string) => {
setValue((prev) => ({
...prev,
travelRecords: reject(
({ id: itemId }) => itemId === id,
prev.travelRecords
),
}));
},
[setValue]
);
const enterLocation = useCallback(
(location: Location & { inputType: travelRecordInputType }) => {
const id = uuid();
const now = dayjs();
const record = {
...location,
id,
inTime: now.toISOString(),
outTime: now.add(4, "hour").toISOString(),
};
createTravelRecord(record);
browserHistory.push({ pathname: `/confirm/${id}`, state: record });
},
[createTravelRecord, browserHistory]
);
return {
travelRecords,
currentTravelRecord,
pastTravelRecord,
createTravelRecord,
getTravelRecord,
updateTravelRecord,
removeTravelRecord,
setAutoRemoveRecordDay,
autoRemoveRecordDay,
enterLocation,
};
})
Example #10
Source File: generateModelFile.ts From kanel with MIT License | 4 votes |
generateModelFile = (
model: TableModel | ViewModel,
{
typeMap,
userTypes,
schemaName,
nominators,
externalTypesFolder,
schemaFolderMap,
makeIdType,
}: {
typeMap: TypeMap;
userTypes: (string | any)[];
schemaName: string;
nominators: Nominators;
externalTypesFolder?: string;
schemaFolderMap: { [schemaName: string]: string };
makeIdType: (innerType: string, modelName: string) => string;
}
): string[] => {
const fileNominator = nominators.fileNominator;
const makeIdName = (name) =>
nominators.idNominator(nominators.modelNominator(name), name);
const lines = [];
const { comment, tags } = model;
const importGenerator = new ImportGenerator(schemaFolderMap[schemaName]);
const referencedIdTypes = pipe(
filter((p: Column) => Boolean(p.reference)),
map((p) => p.reference),
reject((p: Reference) => p.schema === schemaName && p.table === model.name),
uniq
)(model.columns);
referencedIdTypes.forEach((i) => {
const givenName = nominators.modelNominator(i.table);
importGenerator.addImport(
makeIdName(i.table),
false,
path.join(schemaFolderMap[i.schema], fileNominator(givenName, i.table)),
false
);
});
const cols = map(
({ isArray, type, subType, ...rest }) => ({
type: isArray ? subType : type,
...rest,
}),
model.columns
);
const appliedUserTypes = uniq(
map(
(p: Column | { type: string }) => p.type,
filter((p) => userTypes.indexOf(p.type) !== -1, cols)
)
);
appliedUserTypes.forEach((t) => {
const givenName = nominators.typeNominator(t);
importGenerator.addImport(
givenName,
true,
path.join(schemaFolderMap[schemaName], fileNominator(givenName, t)),
false
);
});
const overriddenTypes = map(
(p: Column) => p.tags.type as string,
filter((p) => Boolean(p.tags.type), model.columns)
);
forEach((importedType) => {
const givenName = importedType; // We expect people to have used proper casing in their comments
importGenerator.addImport(
givenName,
true,
path.join(externalTypesFolder, fileNominator(givenName, importedType)),
false
);
}, overriddenTypes);
const primaryColumns = filter((c) => c.isPrimary, model.columns);
// If there's one and only one primary key, that's the identifier.
const hasIdentifier = primaryColumns.length === 1;
const properties = model.columns.map((c) => {
const isIdentifier = hasIdentifier && c.isPrimary;
const idType = isIdentifier && makeIdName(model.name);
const referenceType = c.reference && makeIdName(c.reference.table);
let rawType = c.tags.type || idType || referenceType || typeMap[c.type];
if (typeof rawType === 'boolean') {
throw new Error('@type tag must include the actual type: "@type:string"');
}
if (typeof rawType === 'object') {
importGenerator.addImport(
rawType.name,
rawType.defaultImport,
rawType.absoluteImport
? rawType.module
: path.join(
externalTypesFolder || schemaFolderMap[schemaName],
rawType.module
),
rawType.absoluteImport
);
rawType = rawType.name;
}
if (!rawType) {
console.warn(`Unrecognized type: '${c.type}'`);
rawType = nominators.typeNominator(c.type);
}
const typeName = c.nullable ? `${rawType} | null` : rawType;
const modelAttributes = {
commentLines: c.comment ? [c.comment] : [],
optional: false,
};
const initializerAttributes = {
omit: c.generated === 'ALWAYS',
commentLines: c.comment ? [c.comment] : [],
optional: c.defaultValue || c.nullable,
};
if (c.defaultValue) {
initializerAttributes.commentLines.push(
`Default value: ${c.defaultValue}`
);
}
c.indices.forEach((index) => {
const commentLine = index.isPrimary
? `Primary key. Index: ${index.name}`
: `Index: ${index.name}`;
modelAttributes.commentLines.push(commentLine);
initializerAttributes.commentLines.push(commentLine);
});
return {
name: nominators.propertyNominator(c.name, model),
optional: false,
typeName,
modelAttributes,
initializerAttributes,
};
});
const importLines = importGenerator.generateLines();
lines.push(...importLines);
if (importLines.length) {
lines.push('');
}
if (hasIdentifier) {
const [{ type, tags }] = primaryColumns;
const innerType = (tags.type ||
typeMap[type] ||
nominators.typeNominator(type)) as string;
lines.push(
`export type ${makeIdName(model.name)} = ${makeIdType(
innerType,
model.name
)}`
);
lines.push('');
}
const givenName = nominators.modelNominator(model.name);
const interfaceLines = generateInterface({
name: givenName,
properties: properties.map(({ modelAttributes, ...props }) => ({
...props,
...modelAttributes,
})),
comment,
exportAsDefault: true,
});
lines.push(...interfaceLines);
const generateInitializer = !tags['fixed'] && model.type === 'table';
if (generateInitializer) {
lines.push('');
const initializerInterfaceLines = generateInterface({
name: nominators.initializerNominator(givenName, model.name),
properties: properties
.filter((p) => !p.initializerAttributes.omit)
.map(({ initializerAttributes, ...props }) => ({
...props,
...initializerAttributes,
})),
comment,
exportAsDefault: false,
});
lines.push(...initializerInterfaceLines);
}
return lines;
}
Example #11
Source File: processSchema.ts From kanel with MIT License | 4 votes |
processSchema = async (
schemaConfig: SchemaConfig,
schema: Schema,
typeMap: TypeMap,
nominators: Nominators,
modelProcessChain: Hook<Model>[],
typeProcessChain: Hook<Type>[],
schemaFolderMap: { [schemaName: string]: string },
makeIdType: (innerType: string, modelName: string) => string
) => {
const { tables, views, types } = schema;
const { compositeTypes, enumTypes } = getSupportedTypes(types);
enumTypes.forEach((t) => {
const typeFileLines = generateTypeFile(t, nominators.typeNominator);
const wetTypeFileLines = applyHooks(typeProcessChain, t, typeFileLines);
const givenName = nominators.typeNominator(t.name);
const filename = `${nominators.fileNominator(givenName, t.name)}.ts`;
writeFile({
fullPath: path.join(schemaConfig.modelFolder, filename),
lines: wetTypeFileLines,
});
});
const models = [
...tables.map((t) => ({ ...t, type: 'table' } as const)),
...views.map((t) => ({ ...t, type: 'view' } as const)),
];
const rejectIgnored = reject((m: { name: string }) =>
(schemaConfig.ignore || []).some((matcher) => isMatch(m.name, matcher))
);
const includedModels = rejectIgnored(models);
const userTypes = pluck('name', types);
const tableOrViewTypes = pluck('name', includedModels);
compositeTypes.forEach((t) => {
const typeFileLines = generateCompositeTypeFile(t, {
typeMap,
userTypes,
tableOrViewTypes,
nominators,
schemaName: schemaConfig.name,
externalTypesFolder: schemaConfig.externalTypesFolder,
schemaFolderMap,
});
const wetTypeFileLines = applyHooks(typeProcessChain, t, typeFileLines);
const filename = `${nominators.fileNominator(
nominators.typeNominator(t.name),
t.name
)}.ts`;
writeFile({
fullPath: path.join(schemaConfig.modelFolder, filename),
lines: wetTypeFileLines,
});
});
includedModels.forEach((m) => {
const modelFileLines = generateModelFile(m, {
typeMap,
userTypes,
nominators,
schemaName: schemaConfig.name,
externalTypesFolder: schemaConfig.externalTypesFolder,
schemaFolderMap,
makeIdType,
});
const wetModelFileLines = applyHooks(modelProcessChain, m, modelFileLines);
const filename = `${nominators.fileNominator(
nominators.modelNominator(m.name),
m.name
)}.ts`;
writeFile({
fullPath: path.join(schemaConfig.modelFolder, filename),
lines: wetModelFileLines,
});
});
const indexFileLines = generateIndexFile(
includedModels,
userTypes,
nominators
);
const wetIndexFileLines = applyHooks(
modelProcessChain,
undefined,
indexFileLines
);
writeFile({
fullPath: path.join(schemaConfig.modelFolder, 'index.ts'),
lines: wetIndexFileLines,
});
}