Last active
December 28, 2018 13:40
-
-
Save nabiltntn/e543fd4fc0a33c0546ad91562cb0436f to your computer and use it in GitHub Desktop.
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 { createResolver } from 'apollo-resolvers'; | |
| import { isInstance } from 'apollo-errors'; | |
| import winston from 'winston'; | |
| import _ from 'lodash'; | |
| import Errors from '../errors'; | |
| import Constants from '../constants'; | |
| import Configuration from '../configuration'; | |
| // Simple resolvers call tracking logic | |
| const trackAction = ({ userId, ...actionTracking }, data) => { | |
| if (actionTracking) { | |
| winston.info(JSON.stringify( | |
| { | |
| userId, | |
| ...actionTracking, | |
| data, | |
| timestamp: Date.now(), | |
| })); | |
| } | |
| }; | |
| /** | |
| * Exectue as normal resolver and track action if result is OK | |
| * trackDetails : Object | Function ( that returns object) | |
| **/ | |
| const executeWithTracking = (resolver, root, args, context, trackDetails) => | |
| Promise.resolve(resolver(root, args, context)) | |
| .then((res) => { | |
| if (trackDetails) { | |
| // If trackDetails is a function then execute with arg as parameters | |
| const trackDetailsResult = _.isFunction(trackDetails) ? | |
| trackDetails(args) : trackDetails; | |
| // If trackDetailsResult provides userId then use it ( For login ) | |
| const trackInfos = trackDetailsResult.userId ? | |
| trackDetailsResult : { userId: context.user.userId, ...trackDetailsResult }; | |
| trackAction(trackInfos, args); | |
| } | |
| return res; | |
| }); | |
| // Base resolver definition | |
| const baseResolver = createResolver( | |
| null, | |
| (root, args, context, error) => { | |
| winston.error(error); | |
| return isInstance(error) ? error : new Errors.UnknownError(); | |
| }); | |
| // For resolvers that do not require authenticated users | |
| export const unauthenticatedResolver = (resolver, trackDetails) => | |
| baseResolver.createResolver((root, args, context) => | |
| executeWithTracking(resolver, root, args, context, trackDetails)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment