Saving Functions as module settings

Cccjmk3/4/2022
@Wasp I remember you asked about saving functions as settings (which quickly turned into stringifying them IIRC?), did you end up doing something about that ? I am sort of in dire need of the same haaha EDIT I'll thread this to keep the convo focused
Cccjmk3/4/2022
In particular, I need to save the Commands for Commander, that have several inner functions (looking for an example)
Wwasp3/4/2022
I did not, no - but if you were to stringify the function and then eval(settingString)() you can at least call it
Cccjmk3/4/2022
is it just plain
const myFunction = () => {...}
const funcStr = JSON.stringify(myFunction)
// save funcStr ?

??? I recalled we had to do some processing to it
Cccjmk3/4/2022
like rehydrating the function using a new Function(..) and stuff
Wwasp3/4/2022
Yeah, eval and new Function I believe will both work
Cccjmk3/4/2022
for ref, this is what I want to save (objects with this shape)

{
    name: "tae",
    description: "Token Active Effect",
    schema: "tae $effect",
    args: [{
      name: 'effect',
      type: 'string',
      suggestions: (...) => {...}, // function
    }],
    allow: (...) => {...}  // function
    handler: (...) => {...}  // function
}
Cccjmk3/4/2022
hmm ok, I will play a little bit and report back probably later today 😆
Cccjmk3/4/2022
thanks!
LTLLLeo The League Lion3/4/2022
@ccjmk gave :vote: LeaguePoints™ to @Wasp (#6 • 386)
UUUnknown User3/4/2022
Message Not Public
Sign In & Join Server To View
Cccjmk3/4/2022
I landed here https://stackoverflow.com/a/40876342 looks like the same approach, will give this a try later today! 🙂 this pesky thing called work got in the middle 😆
Cccjmk3/5/2022
In case you were still looking into it Wasp, this is what I did:

export function persistCommandInLocalStorage(command: Command) {
  const serializedCommand = JSON.stringify(command, replacer, 2);
  const key = `cmd-${getCommandSchemaWithoutArguments(command)}`;

  const storedCommands = new Map(JSON.parse(localStorage.getItem(LS_KEY) ?? '[]'));
  storedCommands.set(key, serializedCommand);
  localStorage.setItem(LS_KEY, JSON.stringify([...storedCommands]));
}

export function retrieveCommandsFromModuleSetting(): Command[] {
  const storedCommands = new Map(JSON.parse(localStorage.getItem(LS_KEY) ?? '[]'));
  return Array.from(storedCommands.values())
    .map(serializedCommand => JSON.parse(serializedCommand as string, reviver));
}

const replacer = (key: string, value: unknown) => {
  return typeof value === 'function' ? value.toString() : value;
};

const reviver = (key: string, value: string) => {
  return ['handler', 'allow', 'suggestions'].includes(key) ? new Function(`(${value})`) : value;
};
Cccjmk3/5/2022
Oh it's not really working as expected yet 😦