Last active
April 21, 2019 13:47
-
-
Save towry/af61874ae92067bb4518fde7288c1ea3 to your computer and use it in GitHub Desktop.
Cerebraljs Service provider example, so we can inject cerebral provider into our application layer services, and use application layer services in cerebral application layer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UserAccountService from './UserAccountService'; | |
export function someAction({ services, path }) { | |
let userAccountService = services.get('UserAccountService', UserAccountService); | |
return userAccountService.getUser().then(( { user } ) => { | |
return path.success({ user }) | |
}).catch(err => { | |
return path.error({ error: err}) | |
}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Provider } from 'cerebral'; | |
const services = {}; | |
export default Provider({ | |
get(name, serviceModule) { | |
if (typeof name !== 'string') { | |
throw new TypeError("invalid name"); | |
} | |
if (services.hasOwnProperty(name)) { | |
return services[name]; | |
} | |
if (!serviceModule || typeof serviceModule.create !== 'function') { | |
throw new TypeError(`The service module must have a 'create' method`); | |
} | |
let service = serviceModule.create(this.context); | |
services[name] = service; | |
return service; | |
}, | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ServiceProvider from './ServiceProvider'; | |
const ApiProvider = {}; | |
export default { | |
providers: { | |
services: ServiceProvider, | |
api: ApiProvider, | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class UserAccountService { | |
constructor({ apiProvider }) { | |
this.api = apiProvider; | |
} | |
create({ api }) { | |
return new UserAccountService({ apiProvider: api }); | |
} | |
fetchUser() { | |
return this.api.get('/user'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment