import ioapi from ‘integrator-api’;
//name your state key here
var stateKey = ‘edi840Increments’;
function preMap (options) {
let stateCache;
//get current cache key value, but if cache is not already made then create new cache
try {
stateCache = processCacheRequest(stateKey, options._integrationId, ‘GET’);
} catch (e) {
if (e.message.indexOf(“Unable to locate cache with key”) > -1) {
stateCache = {
interchangeControlNumber: ‘000000001’,
groupControlNumber: ‘000000001’
};
processCacheRequest(stateKey, options._integrationId, ‘PUT’, stateCache);
} else {
throw new Error(e.message);
}
}
//now increment the control numbers by 1
stateCache = {
interchangeControlNumber: lpadIncrement(stateCache.interchangeControlNumber, “0”, 9, 1),
groupControlNumber: lpadIncrement(stateCache.groupControlNumber, “0”, 9, 1)
};
processCacheRequest(stateKey, options._integrationId, ‘PUT’, stateCache, true);
//console.log(JSON.stringify(processCacheRequest(stateKey, options._integrationId, ‘GET’)));
return options.data.map((d) => {
d.cache = stateCache;
return {
data: d
}
})
}
function processCacheRequest (cacheKey, integrationId, method, cacheUpdates, clearCacheFirst) {
if(!cacheKey) throw new Error(‘Missing cacheKey parameter’);
if(!integrationId) throw new Error(‘Missing integrationId parameter’);
var cache = new StateCache({key: cacheKey, integrationId});
if (method === ‘GET’) {
return getCache(cache);
} else if (method === ‘PUT’) {
if (!clearCacheFirst) {
clearCacheFirst = false;
}
return putCache(cache, cacheUpdates, clearCacheFirst);
} else {
throw new Error(‘method !== PUT or GET’);
}
}
function getCache(cache){
return cache.read();
}
function putCache(cache, cacheUpdates, clearCacheFirst){
if (!cacheUpdates) throw new Error(‘!cacheUpdates’);
if (clearCacheFirst) {
cache.clear();
}
return cache.update({cacheUpdates: cacheUpdates});
}
class CacheMissingError extends Error {}
class StateCache {
constructor({key, integrationId}){
this.key = key;
this.integrationId = integrationId;
}
update({cacheUpdates}){
const startingVal = this.read({ignoreMissing: true});
const updatedCacheValue = {…startingVal, …cacheUpdates};
const updateCacheValueRes = ioapi.state.putForResource({
resourceType: 'integrations',
_id: this.integrationId,
key: this.key,
value: updatedCacheValue
});
//console.debug(JSON.stringify(updateCacheValueRes));
return updatedCacheValue;
}
read({ignoreMissing} = {}){
let getCacheValueRes;
try {
getCacheValueRes = ioapi.state.getForResource({
resourceType: ‘integrations’,
_id: this.integrationId,
key: this.key
});
} catch(e) {
if(ignoreMissing)
getCacheValueRes = {};
else
throw new CacheMissingError(Unable to locate cache with key: ${this.key}
);
}
//console.debug(‘getCacheValueRes’, JSON.stringify(getCacheValueRes));
return getCacheValueRes;
}
clear(){
const deleteCacheValueRes = ioapi.state.deleteForResource({
resourceType: ‘integrations’,
_id: this.integrationId,
key: this.key
});
//console.debug(JSON.stringify(deleteCacheValueRes));
}
}