State Provider
The State provider allows you to store data on the Vonage Cloud Runtime platform for your project instances to use. The state provider has a key-value store at its root. As well as lists and maps with various operations you can perform on them.
Functions
You can use the following operations for storing data using the State provider:
Initializing the State Provider
To can access the state provider from a session:
const session = vcr.createSession();
const state = new State(session);
This state is scoped to the session passed into the state initializer, so it can be referred to as session state. When the session reaches its TTL, the stored state will be deleted.
On subsequent calls to your code, you will want to make sure that you are using the same session to have access to your state. You can do so by initializing your instance from an incoming request:
app.post("/onMessage", async (req, res, next) => {
try {
const session = vcr.getSessionFromRequest(req);
const state = new State(session);
// Handle incoming message
} catch (error) {
next(error);
}
});
Account State
Account state is scoped to your Vonage account and is available between all your projects and their instances.
const state = vcr.getAccountState();
Instance State
Instance state is scoped to your instance and deleted when the instance is destroyed. This lets you share context between different sessions in your application.
const state = vcr.getInstanceState();
Use Case
For example, you can store, retrieve, and delete objects on a session using the key-value operations:
app.post("/key-value", async (req, res, next) => {
try {
const session = vcr.createSession();
const state = new State(session);
// store object
await state.set("test_obj", { "foo": bar });
// retrieve object
const obj2 = await state.get("test_obj");
// delete object
await state.del("test_obj");
} catch (error) {
next(error);
}
})
Or you can use instance state, and the hash table operations to persist data between sessions:
app.post("/add-customer", async (req, res, next) => {
try {
const instanceState = vcr.getInstanceState();
const customer = req.body;
await instanceState.mapSet("customers", { [customer.phone]: JSON.stringify(customer) });
res.sendStatus(200);
} catch (error) {
next(error);
}
})
This is storing the customer information in a table with the customer's phone number as the key.
app.get("/on-phone-call", async (req, res, next) => {
try {
const instanceState = vcr.getInstanceState();
const number = req.query.number;
const customer = await instanceState.mapGetValue("customers", number);
res.send(customer.name);
} catch (error) {
next(error);
}
})
Using the customer's number you can retrieve the customer information that was stored earlier.