Serializing and Deserializing
Learn how to manipulate the data you save and retrieve from the database, to more easily store complex data without having to convert it to simple data everywhere you use it.
What are they?
// the default serializer
const serializer = (data, key) => {
return data;
};// the default deserializer
const deserializer = (data, key) => {
return data;
};Examples
Guild Settings: A more sensible example
// Imagine the client and stuff is already defined.
// The function that runs when storing data
const serializeData: data => {
return {
...data,
// stores the guild as ID
guild: guild.id,
// stores the user as ID
user: user.id,
}
};
// This one runs when loading.
const deserializeData: data => {
return {
...data,
// gets the guild itself from the cache from its ID
guild: client.guilds.cache.get(data.guild),
// Same with the user!
user: client.users.cache.get(data.user),
}
};
// Default Settings can no longer store defaults for roles and channels.
const defaultSettings = {
prefix: "!",
modLogChannel: null,
modRole: null,
adminRole: null,
welcomeChannel: null,
welcomeMessage: "Say hello to {{user}}, everyone!"
}
// Our enmap has shiny new options here!
client.settings = new Enmap({
name: "settings",
cloneLevel: 'deep',
serializer: serializeData,
deserializer: deserializeData,
// Might as well autoensure, eh?
autoEnsure: defaultSettings,
});
// Store some data, obviously needs to be run in the right place:
client.settings.set(message.guild.id,
message.mentions.channels.first(),
'welcomeChannel'
);
client.settings.set(message.guild.id,
message.mentions.roles.first(),
'adminRole'
);
// GET the data after
const welcomeChannel = client.settings.get(message.guild.id, 'welcomeChannel');
welcomeChannel.send("This works without having to find or get the channel!");Last updated