feat: add autoConfig/ better types for wrapperData

This commit is contained in:
BluJ
2023-04-19 17:23:16 -06:00
parent 7c4f94ba8f
commit e279711f8e
39 changed files with 431 additions and 291 deletions

View File

@@ -1,18 +1,25 @@
import { Config } from "./builder";
import { DeepPartial, Dependencies, DependsOn, Effects, ExpectedExports } from "../types";
import {
DeepPartial,
Dependencies,
DependsOn,
Effects,
ExpectedExports,
} from "../types";
import { InputSpec } from "./configTypes";
import { nullIfEmpty } from "../util";
import { TypeFromProps } from "../util/propertiesMatcher";
export type Write<A, ConfigType> = (options: { effects: Effects; input: TypeFromProps<A> }) => Promise<ConfigType>;
export type Read<A, ConfigType> = (options: {
effects: Effects;
config: ConfigType;
}) => Promise<null | DeepPartial<TypeFromProps<A>>>;
export type DependenciesFn<A, ConfigType> = (options: {
export type Write<A> = (options: {
effects: Effects;
input: TypeFromProps<A>;
}) => Promise<void>;
export type Read<A> = (options: {
effects: Effects;
}) => Promise<null | DeepPartial<TypeFromProps<A>>>;
export type DependenciesFn<A> = (options: {
effects: Effects;
input: TypeFromProps<A>;
config: ConfigType;
}) => Promise<Dependencies | void>;
/**
* We want to setup a config export with a get and set, this
@@ -21,31 +28,30 @@ export type DependenciesFn<A, ConfigType> = (options: {
* @param options
* @returns
*/
export function setupConfigExports<A extends InputSpec, ConfigType>(options: {
spec: Config<A>;
write: Write<A, ConfigType>;
read: Read<A, ConfigType>;
dependencies: DependenciesFn<A, ConfigType>;
}) {
const validator = options.spec.validator();
export function setupConfigExports<A extends InputSpec>(
spec: Config<A>,
write: Write<A>,
read: Read<A>,
dependencies: DependenciesFn<A>,
) {
const validator = spec.validator();
return {
setConfig: (async ({ effects, input }) => {
if (!validator.test(input)) {
await effects.error(String(validator.errorMessage(input)));
return { error: "Set config type error for config" };
}
const config = await options.write({
await write({
input: JSON.parse(JSON.stringify(input)),
effects,
});
const dependencies = (await options.dependencies({ effects, input, config })) || [];
await effects.setDependencies(dependencies);
await effects.setWrapperData({ path: "config", value: config || null });
const dependenciesToSet = (await dependencies({ effects, input })) || [];
await effects.setDependencies(dependenciesToSet);
}) as ExpectedExports.setConfig,
getConfig: (async ({ effects, config }) => {
return {
spec: options.spec.build(),
config: nullIfEmpty(await options.read({ effects, config: config as ConfigType })),
spec: spec.build(),
config: nullIfEmpty(await read({ effects })),
};
}) as ExpectedExports.getConfig,
};