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 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 ?
const myFunction = () => {...}
const funcStr = JSON.stringify(myFunction)
// save funcStr ?
??? I recalled we had to do some processing to it 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
}
{
name: "tae",
description: "Token Active Effect",
schema: "tae $effect",
args: [{
name: 'effect',
type: 'string',
suggestions: (...) => {...}, // function
}],
allow: (...) => {...} // function
handler: (...) => {...} // function
}
hmm ok, I will play a little bit and report back probably later today 😆 thanks!
LTLLeo The League Lion3/4/2022
@ccjmk gave vote LeaguePoints™ to @wasp (#6 • 386)
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 😆
Stack Overflow
JavaScript - Save object with methods as a string
I've been looking around for a way to do this but can't seem to find anything, I have different configuration objects that I need to save as a text in variables for some processing later on, here i...
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;
};
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;
};
Oh it's not really working as expected yet 😦

Looking for more? Join the community!

Want results from more Discord servers?
Add your server
Recommended Posts
new consumable typesTried adding localization strings for some new consumable types, but keep getting this ("`DND5E.Consspell-compendium-5e alpha1Overriding onDropItem & onSortItemYou'd override them in your sheet class.getter & setter wrapper for settingsI'm trying to use a getter & setter pair as an interface for `game.settings.get` and `game.settings.scrollable tab contentsIt is possible, and you're firmly in the css and DOM structure side of development with this line ofJr devI'm cleaning out my bookmarks and accidentally came back to this article. Potentially useful startinHTCPackage: `hero-creation-tool`System Specific CSSI'm not 100% about this, but it is worth watching out that your solution doesn't actually end up beiadvancement-wipCommander register apitalking about permissions, im working on the registering api for the Commander, and I wanted to ask Azgaars Blurry MapHey all. I'm taking a look at my importer for Azgaar's Fantasy Map Generator and wondering how I canccjmk overlaybut for what I wanted I think I *needed* to append it there so that I can overlay the whole screencliits very very early alpha demoMonarch APIAlright, adventurous ones: I have a Beta version of Monarch with the new components API! Manifest: compacted chat cardsModules create problems to solve problems... Today's problem: "When I roll an attack, it eats the whdragdrop shenneneginsRight now, a user can drag a spell onto their character sheet. I store that in a 'spell' array and leffect mini modulesI've gotten to the point where I'm confident in releasing a slurry of tiny no-config Active Effect rdamage application hooksNew 5e Hook ideas, gimme yer thoughts: `Hooks.call('Actor5e.preDamageApplied')` args: `damageAmounthook conventionsRegarding hooks, is the convention that _all_ `pre...` hooks are executed on the machine that initiaexpand arraysIs there a way to `expandObject` except for an Array?