Skip to content
Snippets Groups Projects
set.ts 1.91 KiB
Newer Older
  • Learn to ignore specific revisions
  • Marin Karamihalev's avatar
    Marin Karamihalev committed
    import { DecodeFn } from "../../types";
    import { searchAll } from "../util";
    
    import {
      EncodeFn,
      SetLookupUpdateObject,
      SetLookupUpdateParamSetting,
    } from "../../types";
    import * as util from "../util";
    
    Marin Karamihalev's avatar
    Marin Karamihalev committed
    import { parseSetArgs } from "../../util";
    
    const decode: DecodeFn = (msg, decodeOptions) => {
      if (decodeOptions?.raw) return [msg];
    
    Marin Karamihalev's avatar
    Marin Karamihalev committed
      const affected = searchAll(msg, "updatedInstResults");
      return [affected];
    };
    
    const isObject = (v) =>
      typeof v === "object" && v.required !== undefined && v.value !== undefined;
    
    const makePairs = (path: string, value): [string, any, boolean][] =>
      path.endsWith(".") && typeof value === "object" && value !== null
        ? Object.entries(value as any[]).map(([k, v]) =>
            isObject(v)
              ? [k, v.value.toString(), "required" in v && Boolean(v.required)]
              : [k, v.toString(), true]
          )
        : [[path.split(".").pop() || "", (value || "").toString(), true]];
    
    const encode: EncodeFn = ({ value, path: initialPath }) => {
    
    Marin Karamihalev's avatar
    Marin Karamihalev committed
      const [paths, values] = parseSetArgs(value, initialPath);
    
      const allowPartial =
    
        (values && values.some((it) => it.allowPartial)) || true;
    
    
      const updateObjs = paths.map((path, i) => ({
        lookup: "Set.UpdateObject" as SetLookupUpdateObject,
        objPath: path.endsWith(".")
          ? path
          : path.slice(0, path.lastIndexOf(".") + 1),
        paramSettings: makePairs(path, values[i])
          .filter(([k]) => k !== "allowPartial")
          .map(([param, value, required]) => ({
            lookup: "Set.UpdateParamSetting" as SetLookupUpdateParamSetting,
            param,
            value,
            required,
          })),
      }));
    
      return {
        lookup: "Msg",
        header: {
          lookup: "Header",
          msgId: util.uniq("SET@"),
          msgType: "SET",
        },
        body: {
          lookup: "Body",
          request: {
            lookup: "Request",
            set: {
              allowPartial,
              updateObjs,
            },
          },
        },
      };
    };
    
    export default {
      decode,
      encode,
    };