Skip to content

Instantly share code, notes, and snippets.

@brunoguerra
Last active September 12, 2016 05:56
Show Gist options
  • Save brunoguerra/26ecb4b15631301f5db707ed01ad6950 to your computer and use it in GitHub Desktop.
Save brunoguerra/26ecb4b15631301f5db707ed01ad6950 to your computer and use it in GitHub Desktop.
Angular 1.5 :~
import angular from 'angular';
// fn
const normaliz = ( entities ) => ( {
entities: entities.reduce( (r, e) => Object.assign( r, { [e._id]: e } ), {} ),
ids: entities.map( d => d._id )
} );
const storeItem = ( item ) => ( value ) =>
window.localStorage[item] = JSON.stringify( value );
const restoreItem = ( item ) => JSON.parse( window.localStorage[item] );
const updateItem = ( trans ) => ({
entities: Object.assign({}, trans.col.entities, {
[trans.item._id]: trans.item
}),
ids: Array.from(new Set([...trans.col.ids, trans.item._id]))
});
const normalizEmpty = normaliz( [] );
const register = ( store, name ) => Object.assign( register.stores, {
[name]: store
} ) && store;
register.stores = {};
const store = ( store ) => {
const storer = storeItem( store );
const restorer = () => restoreItem( store ) || normalizEmpty;
const reducer = {
writer: ( result ) =>
storer( normaliz( result.data ) ) &&
result,
reader: ( id ) => restorer().entities[id],
updater: ( result ) => storer( updateItem( {
col: restorer(),
item: result.data
} ) )
};
return register( reducer, store );
}
// reducers
const documentsStore = store( 'documents' );
const usersStore = store( 'users' );
// Service
function Backend( $http, BackendUrl ) {
'ngInject';
const backend = this;
// create rest request method with subset methods
// this.$get to pick up one from cache
// this.storesX => get
const rest = ( store ) => {
const s = register.stores[store];
const url = BackendUrl + `/${store}/`;
const catcher = catchError( store );
const extras = {
[store]: () => $http.get( url ).then(
s.writer,
catcher( { url, action: 'index' } )
),
[store + '$get']: s.reader,
[store + '$update']: ( item ) => $http.put( url, {
data: item
} ).then(
s.updater,
catcher( { url, action: 'update', item } )
)
};
return Object.assign( backend, extras );
};
rest( 'documents' );
rest( 'users' );
}
// Helpers
function catchError( store ) {
const type = 'backend';
return ( data ) => ( e ) => {
console.log( `Error on fetching ${store}`, e );
window.lastError = e;
window.fire( 'error', { e, type, data } );
return e;
};
}
// Module
const module = angular.module( 'app.backend', [] )
module.service( 'Backend', Backend );
// exports
export default module;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment