Examples
Obtain an API token: getkey()
PrefsDB.getkey() generates a new API token - if one does not exist. If a token exists, the method simply returns the existing token, so it is safe to call it multiple times. The function accepts the following parameters:
| parameter name | type | description |
|---|---|---|
| name | string | Plain text string identifying this key, e.g. your app's name. |
| seed | array[string] | API token building blocks. Can be a combination of secret, user supplied, and public data. |
| options | object | Optional. email (needed when a new key is created), onsuccess/onerror callbacks, timeout, etc. See Options. |
Include prefsdb.com in your project
Generate an API token (a.k.a. API Key):
Hint: Secrets should never be displayed or sent anywhere. For instance, if using login form, capture those values and right away generate an API token.
Basic write operation
The segment below illustrates how to obtain an API token (using PrefsDB.getkey()) and then write a single value once a token is received.
Notice that both writes use the same key, greeting: the second write overrides the value set by the first.
/*
* Wait for an API Token, then write a value - twice.
*/
const db = await PrefsDB.getkey("key-id", ["secret1", "secret2"]);
await db.key("greeting").write("Hello World!");
await db.key("greeting").write("Hey there World!");
/*
* Retrieve data to confirm, but note that it holds the value
* of the last write operation. Keys are mutable and will be overwritten.
*/
const R = await db.key("greeting").read();
const greeting = R.value;
// greeting will now hold "Hey there World!"
curl -s -b cookies.txt -H "X-Authorization: Token $KEY" \
-G https://prefsdb.com/api/v1/write/ --data-urlencode "greeting=Hello World!"
curl -s -b cookies.txt -H "X-Authorization: Token $KEY" \
-G https://prefsdb.com/api/v1/write/ --data-urlencode "greeting=Hey there World!"
curl -s -b cookies.txt -H "X-Authorization: Token $KEY" \
-G https://prefsdb.com/api/v1/read/ -d "greeting="
Write key/value pair
Next example, will write a value identified by a key (as per key/value concept). Remember that scope of the key will depend on the seed values used when an API token was generated. If a token is generated for per user, any data stored with that key will be applicable to that user only.
The above can also be written out in a single stroke like this:
Basic read operations
Saved data can be retrieved with a .read() function.
Read ALL values associated with a key.
Hint
All key/value pairs can be grouped by project name, domain, and subdomain grouping directives.
See: Organizing data
Key/value Example: Store game data for a user
<script src="https://prefsdb.com/prefsdb.v1.min.js"></script>
<input type="text" id="inputbox1" placeholder="email" />
<input type="password" id="inputbox2" />
<script>
/*
* Things we want stored for the user, can be a string, or an object.
*/
let user_data = { level: 5, score: 200 };
function getKey() {
const userName = document.getElementById("inputbox1").value;
const userPass = document.getElementById("inputbox2").value;
// The email is only needed (and only used) the first time, to verify the new key.
return PrefsDB.getkey("myFirstKey", [userName, userPass, "mysalt"], { email: userName });
}
/*
* Called when 'Save' button clicked.
*/
async function save_data() {
const db = await getKey();
if (db.emailVerificationRequired()) {
alert("Check your inbox and click the verification link.");
await db.waitForVerification(); // resolves once the link is clicked
}
await db.key("user-data").write(user_data);
}
/*
* Called when 'Read' button clicked.
*/
async function read_data() {
const db = await getKey();
const result = await db.key("user-data").read();
if (result.success) {
user_data = result.value;
}
}
</script>
<button onclick="save_data()">Save user data</button>
<button onclick="read_data()">Get user data</button>
The key generated will be isolated and unique to your user. Any data written with that key, can only be retrieved having provided the same exact seed parameters.
List example: Collect emails from a product landing page
The page is a typical landing page for a "ProductX" and offers an input box where users can enter an email address to be notified when ProducX launches. The code snippet illustrates how to capture user input and add it to the list called "launchEmails".
Warning
Every visitor of this page uses the same key, and anyone who reads the page's source can see its seed — so anyone could also read or delete the collected addresses. Use this pattern for demos. For real sign-ups, keep the key on a server (e.g. a key issued from your dashboard) and send the addresses there.
<script src="https://prefsdb.com/prefsdb.v1.min.js"></script>
<input type="text" id="inputbox" />
<script>
/*
* Called when 'Notify Me' button clicked.
*/
async function save_data() {
const userEmail = document.getElementById("inputbox").value;
const db = await PrefsDB.getkey("ProductX", ["salt1", "salt2"]);
await db.project("ProductX").list("launchEmails").add(userEmail);
}
</script>
The key has to exist (and be verified) before visitors can use it, so create it once yourself first, e.g. from your browser's console on that page: await PrefsDB.createkey("ProductX", ["salt1", "salt2"], { email: "you@example.com" }), then click the link in the email.
The list can be retrieved at any time:
<script src="https://prefsdb.com/prefsdb.v1.min.js"></script>
<script>
(async () => {
const db = await PrefsDB.getkey("ProductX", ["salt1", "salt2"]);
// array: true -- R.values is an array however many entries there are
const R = await db.project("ProductX").list("launchEmails").read({ array: true });
if (R.success) {
const emails = R.values;
}
})();
</script>
(There's no cURL version of this one: the key belongs to the page's origin, so it's only reachable from that site.)