Skip to content

Examples

Obtain an API token: GetKey()

Getkey() function generates a new API token - if one does not exist. If a token exists, the method simply echoes back the existing token, so it is safe to call it multiple times. The function accepts the following parameters:

parameter name type description
key-id string Plain text string identifying this key
(reserved for future use).
seed array[string] API token building blocks. Can be a combination of secret, user supplied, and public data.
callback function Callback function. Check result.status for 'success' or 'error'.

Include prefs.us in your project

<script src="https://prefs.us/prefs.us.js"></script>

Generate a an API token (a.k.a. API Key) , then retrieve it via a callback:

prefs_us.getkey('key-id', [ 'secret1', 'secret2', ... ],
    (response) => {
        console.log("API Key: " + response.token);
    }
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 .getkey()) and then write a single value once a token is received. Notice, that in this example we don't provide a key for the data. Any subsequent calls to .write will override previously set value.

/*
 * Wait for an API Token via a callback, then write a value - twice.
 */ 
prefs_us.getkey('key-id', [ 'secret1', 'secret2', ... ],
    (response) => {
        prefs_us.write("Hello World!");
        prefs_us.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 overwrtitten.
 */ 
prefs_us.read((R)=>{
    let greeting = R.value;
    //  greeting will now hold "Hey there World!"
});

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.

prefs_us.key('theme').write('dark');
prefs_us.key('timeout').write('300');
prefs_us.key('game-stats').write('{ "score":"100", "level":"6" }');

The above can also be written out in a single stroke like this:

prefs_us.key('user-data').write('{ "theme":"dark", "timeout":"300", "score":"100", "level":"6" }');

Basic read operations

Saved data can be retrieved with a .read() function.

prefs_us.key('user-data').read( (result) => {
    console.log("Got data: %o", ressult.values);
});

Read ALL values associated with a key.

prefs_us.readAll( (result) => {
    console.log("all values: %o", ressult.values);
});

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://prefs.us/prefs.us.js"></script>

<input type="text"  id="inputbox1" />
<input type="password" id="inputbox2" />

<script>
/*
 * Things we want stored for the user, can be a string, or an object.
 */
var user_data = '{ "level": "5", "score": "200" }';

/*
 * Called when 'Save' button clicked.
 */
function save_data() {
   let userName = document.getElementById("inputbox1").value;
   let userPass = document.getElementById("inputbox2").value;

   prefs_us.getkey('myFirstKey', [userName, userPass, 'mysalt' ], (response) => {
       prefs_us.key("user-data").write(user_data);
   });
}

/*
 * Called when 'Read' button clicked.
 */
function read_data() {
   let userName = document.getElementById("inputbox1").value;
   let userPass = document.getElementById("inputbox2").value;

   prefs_us.getkey('myFirstKey', [userName, userPass, 'mysalt' ], (response) => {
       prefs_us.read( (result) => {
           if (response.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".

<script src="https://prefs.us/prefs.us.js"></script>

<input type="text" id="inputbox" />

<script>
/*
 * Called when 'Notify Me' button clicked.
 */
function save_data() {
   let userEmail = document.getElementById("inputbox").value;

   prefs_us.getkey('ProductX', ["salt1", 'salt2' ], (response) => {
       prefs_us.project("ProductX").list("launchEmails").add(userEmail);
   });
}
</script>
The list can be retrieved at any time:
<script src="https://prefs.us/prefs.us.js"></script>

<script>
    prefs_us.getkey('ProductX', ["salt1", 'salt2' ], (response) => {
        prefs_us.project("ProductX").list("launchEmails").read( (R)=>{
            if (R.success) {
                let emails = R.values;
            }
        });
    });
</script>