1.3.1 • Published 6 years ago
gcp-redux v1.3.1
gcp-redux
Binds a Redux store to Google Cloud Datastore
This package is written in ES2015 (ES6).
Installation
npm install --save gcp-redux
## Usage
You can use the Datastore emulator to run this example: https://cloud.google.com/datastore/docs/tools/datastore-emulator
const GCPRedux = require('gcp-redux');
// A basic reducer for a counter
const reducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
}
return state;
};
// Will be called on error
const error_handler = (err) => {
console.error('Error:', err);
process.exit(1);
};
// Minimum configuration
// See Datastore documentation
const config = {
id: 'Test',
kind: 'TestKind',
datastore: {
projectId: 'MyProjectID' // Use an actual project id
}
};
const store = new GCPRedux(config, reducer);
// Watch for errors
store.on('error', error_handler);
// Log the new state when store is updated
const watcher = () => {
console.log('New state:', store.getState());
};
// Initialize the store with the last saved state if any
store.init()
.then(() => {
console.log('Current state:', store.getState());
store.subscribe(watcher);
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
}).catch(error_handler);
Run this example multiple times to see that the state is stored.
Datastore connection
If you already are connected to Datastore, you can use that connection using the third constructor argument.
const Datastore = require('@google-cloud/datastore');
const connection = Datastore({ projectId: 'MyProjectId' });
const store = new GCPRedux({ id: 'anyId' }, reducer, connection);
store.init()
.then(() => {
// ...
});