Feat: Type-safety using a FactTypeMapping
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 5/5
- Tempo estimado
- Mais de uma semana
- Facilidade para iniciantes
- 25/100
- Tipo de issue
- Funcionalidade
- Clareza
- Razoavelmente clara
- Status de atividade
- Estagnada
- Stack de tecnologia
- javascript, typescript
- Domínio
- backend-api-design
Direção de pesquisa
Comece pelas declarações públicas representadas por engineFactory, Engine, Almanac e Fact. Compare a inferência baseada em dicionário proposta com o uso genérico atual; concluído significa que a API suportada, o comportamento da inferência e a política de breaking changes foram acordados e validados.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
We're doing a quick POC and looking at using this library. One thing that I'd love to see is the ability to enforce or at least make consistent the concept of fact types. Something along the lines of:
type Dictionary = {
userId: number;
};
const engine = rulesEngine<Dictionary>([]);
engine.addFact("userId", 1);
// Not Valid:
// engine.addFact("userId", false);
expectType<Fact<number, Dictionary>>(engine.getFact("userId"));
expectType<Fact<unknown, Dictionary>>(engine.getFact("other"));
engine.addFact("userId", (params, almanac) => {
expectType<Almanac<Dictionary>>(almanac);
expectType<Promise<number>>(almanac.factValue("userId"));
expectType<Promise<unknown>>(almanac.factValue("other"));
return 43;
});
You get the idea. Let users specify a dictionary of facts whose type is known ahead of time and fixed. Today, this is kind of done by just letting the user set the type of the fact value, but it doesn't carry through the system.
I took an initial stab at doing this which is below, but the issue is that this would require a breaking type change.
Today since users can specify the type almanac.factValue<number>('userId'). But in order to infer types, we'd need to template the key-type as well, giving us two generics. TS doesn't like having partially filled out generics...so we hit an impasse: if we want to allow user overriding of the types, then we'll need to ask people to specify <number, string> where before it was just <number>.
Of course the ideal scenario is that they remove the template together and just pass a dictionary of types on engine construction; changing this usage would be smoothest by default, but they could still override the type by casting through any (or we could make any the default instead of unknown).
Here's the new ts file, complete with changes if anyone would like to play around further or discuss more.
View Code
export interface EngineOptions {
allowUndefinedFacts?: boolean;
allowUndefinedConditions?: boolean;
pathResolver?: PathResolver;
}
export interface EngineResult<FactTypeDictionary> {
events: Event[];
failureEvents: Event[];
almanac: Almanac<FactTypeDictionary>;
results: RuleResult[];
failureResults: RuleResult[];
}
export default function engineFactory<
FactTypeDictionary extends Record<string, any> = {}
>(
rules: Array<RuleProperties<FactTypeDictionary>>,
options?: EngineOptions
): Engine<FactTypeDictionary>;
// This helper gives us optionality. If the key is in the dictionary, then we return the type,
// otherwise we return the default type which is unknown (unless the user specifies it on the call itself)
type FactReturn<
Dictionary,
Key,
Default = unknown
> = Key extends keyof Dictionary ? Dictionary[Key] : Default;
export class Engine<FactTypeDictionary extends Record<string, any> = {}> {
constructor(
rules?: Array<RuleProperties<FactTypeDictionary>>,
options?: EngineOptions
);
addRule(rule: RuleProperties<FactTypeDictionary>): this;
removeRule(ruleOrName: Rule | string): boolean;
updateRule(rule: Rule): void;
setCondition(name: string, conditions: TopLevelCondition): this;
removeCondition(name: string): boolean;
addOperator(operator: Operator): Map<string, Operator>;
addOperator<A, B>(
operatorName: string,
callback: OperatorEvaluator<A, B>
): Map<string, Operator>;
removeOperator(operator: Operator | string): boolean;
addFact<T>(fact: Fact<T>): this;
addFact<DefaultValueType, Key extends string>(
id: Key,
valueCallback:
| DynamicFactCallback<
FactReturn<FactTypeDictionary, Key, DefaultValueType>,
FactTypeDictionary
>
| FactReturn<FactTypeDictionary, Key, DefaultValueType>,
options?: FactOptions
): this;
removeFact(factOrId: string | Fact<any>): boolean;
getFact<Key extends string>(
factId: Key
): Fact<FactReturn<FactTypeDictionary, Key>, FactTypeDictionary>;
on(eventName: "success", handler: EventHandler<FactTypeDictionary>): this;
on(eventName: "failure", handler: EventHandler<FactTypeDictionary>): this;
on(eventName: string, handler: EventHandler<FactTypeDictionary>): this;
// TODO: This run keyset should optionally reference the types from FactTypeDictionary
run(facts?: Record<string, any>): Promise<EngineResult<FactTypeDictionary>>;
stop(): this;
}
export interface OperatorEvaluator<A, B> {
(factValue: A, compareToValue: B): boolean;
}
export class Operator<A = unknown, B = unknown> {
public name: string;
constructor(
name: string,
evaluator: OperatorEvaluator<A, B>,
validator?: (factValue: A) => boolean
);
}
export class Almanac<FactTypeDictionary> {
// If a path is passed, then we don't have a good way to know the type anymore so we return unknown
factValue<Key extends string, Path>(
factId: Key,
params?: Record<string, any>,
path?: Path
): Promise<
Path extends string ? unknown : FactReturn<FactTypeDictionary, Key>
>;
addRuntimeFact<Key extends string>(
factId: Key,
value: FactReturn<FactTypeDictionary, Key, any>
): void;
}
export type FactOptions = {
cache?: boolean;
priority?: number;
};
export type DynamicFactCallback<T, FactTypeDictionary> = (
params: Record<string, any>,
almanac: Almanac<FactTypeDictionary>
) => T;
export class Fact<T = unknown, FactTypeDictionary = {}> {
id: string;
priority: number;
options: FactOptions;
value?: T;
calculationMethod?: DynamicFactCallback<T, FactTypeDictionary>;
constructor(
id: string,
value: T | DynamicFactCallback<T, FactTypeDictionary>,
options?: FactOptions
);
}
export interface Event {
type: string;
params?: Record<string, any>;
}
export type PathResolver = (value: object, path: string) => any;
export type EventHandler<FactTypeDictionary> = (
event: Event,
almanac: Almanac<FactTypeDictionary>,
ruleResult: RuleResult
) => void;
export interface RuleProperties<FactTypeDictionary = {}> {
conditions: TopLevelCondition;
event: Event;
name?: string;
priority?: number;
onSuccess?: EventHandler<FactTypeDictionary>;
onFailure?: EventHandler<FactTypeDictionary>;
}
export type RuleSerializable = Pick<
Required<RuleProperties<any>>,
"conditions" | "event" | "name" | "priority"
>;
export interface RuleResult {
name: string;
conditions: TopLevelCondition;
event?: Event;
priority?: number;
result: any;
}
// Something like a rule could be constructed outside of the context of an engine.
// For simplicity, we just default it to an empty dictionary since often the types won't come up in the rule definition
// (basically only if you were to attach an event, AND reference factValue from the almanac)
export class Rule<FactTypeDictionary extends Record<string, any> = {}>
implements RuleProperties<FactTypeDictionary>
{
constructor(ruleProps: RuleProperties<FactTypeDictionary> | string);
name: string;
conditions: TopLevelCondition;
event: Event;
priority: number;
setConditions(conditions: TopLevelCondition): this;
setEvent(event: Event): this;
setPriority(priority: number): this;
toJSON(): string;
toJSON<T extends boolean>(
stringify: T
): T extends true ? string : RuleSerializable;
}
interface ConditionProperties {
fact: string;
operator: string;
value: { fact: string } | any;
path?: string;
priority?: number;
params?: Record<string, any>;
name?: string;
}
type NestedCondition = ConditionProperties | TopLevelCondition;
type AllConditions = {
all: NestedCondition[];
name?: string;
priority?: number;
};
type AnyConditions = {
any: NestedCondition[];
name?: string;
priority?: number;
};
type NotConditions = { not: NestedCondition; name?: string; priority?: number };
type ConditionReference = {
condition: string;
name?: string;
priority?: number;
};
export type TopLevelCondition =
| AllConditions
| AnyConditions
| NotConditions
| ConditionReference;
- Linguagem predominante
- JavaScript
- Estrelas
- 3.1k
- Forks
- 507
- Métricas de merge de PRs
- Nenhum PR com merge em 30d
Guia de contribuição
Nenhum guia de contribuição indexado para este repositório
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de CacheControl/json-rules-engine
-
Dificuldade 4/5 3-5 dias Facilidade para iniciantes 35/100
CacheControl/json-rules-engine#427 · 1 reação ·
-
Dificuldade 4/5 3-5 dias Facilidade para iniciantes 35/100
-
Dificuldade 3/5 1-2 dias Facilidade para iniciantes 48/100
CacheControl/json-rules-engine#424 · 1 comentário ·
-
Dificuldade 3/5 1-2 dias Facilidade para iniciantes 25/100
CacheControl/json-rules-engine#421 · 1 comentário ·
-
Dificuldade 3/5 1-2 dias Facilidade para iniciantes 38/100
CacheControl/json-rules-engine#417 · 1 reação ·
Todas as issues de CacheControl/json-rules-engine
Issues semelhantes
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 88/100
HarperFast/skills#96 ·
-
[Block] Latest Posts [Type] Bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
-
Daemon passes --experimental-wasm-jspi unconditionally on Node >= 24; Node 26 rejects the flag Aberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
Automattic/studio#4908 ·
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 74/100
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 86/100
sugarlabs/musicblocks#8847 ·