Skip to content
Danny SMc edited this page May 13, 2021 · 2 revisions

Feature: State

The global state, is an accessible dot notation lookup module for all models, controllers, providers and services, the state is loaded in memory and periodically flushed to the database or file every 30 seconds by default, this can be amended within the framework configuration. If you want to increase then, please be aware that of course flushing quicker could slow down the database database depending on the size of the state.



Retrieving Data

The state is a single object that uses a dot-notation lookup, for example, say this is your state:

{
	sessions: {
		'8a7ea2ae': {
			token: '842b8e8a-8fcd-4f5c-824a-4ca26b211ef3',
			name: 'John Doe',
			email: 'john.doe@example.com',
			position: 'Manager',
		},
		'42930374': {
			token: 'dc616743-59bc-4ab9-81ed-ce90258030b9',
			name: 'Thomas Smith',
			email: 'thomas.smith@example.com',
			position: 'Developer',
		},
		'b66f6b89': {
			token: '3775b9ba-4a02-4fa3-8e0c-27ffade615eb',
			name: 'Adam Jones',
			email: 'adam.jones@example.com',
			position: 'DevOps',
		},
	}
}

You can in any method of a controller, service, model or provider call the following to access for example Thomas's email:

IMPORTANT The state is injected into the class at runtime, therefore, to enable type hinting and prevent type errors, you will need to create a property in your controller, service, provider or model that defines the state, like so: protected state!: State; and make sure to import State from the rewyre package.

const email: string = this.state.get('sessions.42930374.email');

The above will resolve to that section, if something is missing, it will throw an error, so be prepared to catch it. The dot-notation is a clean way of accessing data, if you want to directly access it then you can do:

const email: string = this.state.getStateObject().sessions['42930374'].email;

But we suggest using the dot-notation for a cleaner and easier developing experience, but it's all down to personal preference.



Inserting Data

To insert new data, this is the same concept, you can either apply it directly to the this.state.getStateObject() response, or you can do:

this.state.set('sessions.6ac2c81b', {
	token: 'fb1bfd92-6244-4850-968d-b8b012d9dff3',
	name: 'Sarah Smith',
	email: 'sarah.smith@example.com',
	position: 'Human Resources',
});

Or to set a specific field:

this.state.set('sessions.42930374.email', 'thomas.smith2@example.com');

IMPORTANT If the dot notation goes to a property that does not exist,it will throw an error, so make sure to create the object before trying to access it.

Useful Links:

Clone this wiki locally