Data

Storage

Storage keeps values by key, like a Map, but on disk: what a plugin stores survives a map change and a server restart. It is the place for a player's saved points, his last visit, a preference.

const 
visits
= new
Storage
<number>("myplugin_visits");
server
.
addEventListener
("putInServer", (
event
) => countVisit(
event
.
player
));
function countVisit(
player
: Client) {
const
count
= (
visits
.
get
(
player
.
steamId
) ?? 0) + 1; // undefined when the key is not there
visits
.
set
(
player
.
steamId
,
count
);
console
.
log
(`${
player
.
name
}: visit ${
count
}`);
}
MethodDoes
get(key)the value under key, or undefined
set(key, value)puts value under key, replacing what was there
has(key)true when there is a value under key
delete(key)removes key: true when it was there
keys() since v0.3every key
size since v0.3how many keys it holds
prune(olderThan) since v0.3removes what was last set before a Date; how many keys went

The type argument is what the storage holds since v0.3: text by default (new Storage("name")), or a number, a boolean, an object of an interface - new Storage<Profile>("myplugin_profiles") - kept as JSON.

interface Profile {
    
kills
: number;
title
: string;
} const
profiles
= new
Storage
<Profile>("myplugin_profiles");
const
mine
=
profiles
.
get
(
player
.
steamId
) ?? {
kills
: 0,
title
: "rookie" };
mine
.
kills
++;
profiles
.
set
(
player
.
steamId
,
mine
);
profiles
.
prune
(new
Date
(
Date
.
now
() - 30 * 24 * 3600 * 1000)); // a month untouched
A field added later is optional
get reads a value back in the shape its type has now, and a record kept before you added a field has no such field. Declare a field you add optional and read it with a default: title?: string, then mine.title ?? "rookie". A field of a class with a default (title = "rookie") takes the default.A value that still does not read - a field missing that is neither, a field of another type - makes get throw a TypeError that names the storage, the key and the field, and the value stays on disk: Storage "myplugin_profiles", key "STEAM_0:0:1": JSON: title is missing, text was expected.

The name is the storage's file: new Storage("myplugin_visits") keeps its data in addons/amxmodx/data/amxts/storage/myplugin_visits.json, JSON an admin can read. Give each storage a name of its own, starting with your plugin's name: every plugin that opens a name shares it. A change is on disk within a second, written whole through a temporary file, and when the map changes.

The first time a name has no file, it takes what AMX Mod X's nvault kept under the same name (data/vault/<name>.vault), once: a plugin that moves from Pawn keeps its players' data.