Skip to content

Instantly share code, notes, and snippets.

@holmesal
Created March 4, 2019 20:44
Show Gist options
  • Save holmesal/0c02b41c7f169846dde70e27a4e85a7a to your computer and use it in GitHub Desktop.
Save holmesal/0c02b41c7f169846dde70e27a4e85a7a to your computer and use it in GitHub Desktop.
import {
GraphQLBoolean,
GraphQLError,
GraphQLList,
GraphQLNonNull,
GraphQLString
} from 'graphql';
import {
fromGlobalId,
mutationWithClientMutationId
} from 'graphql-relay';
import assert from 'assert';
import * as types from '../types';
import * as db from '../../db';
import * as actions from '../../actions';
import Promise from 'bluebird';
import log from '../../log';
const pre = '[subscribeToPodcastMutation] ';
import { requireAuthMutation } from '../decorators';
export default mutationWithClientMutationId({
name: 'SubscribeToPodcast',
inputFields: {
podcastId: {
type: new GraphQLNonNull(GraphQLString)
},
autofollowCreators: {
type: GraphQLBoolean,
description: `If true, you'll also automatically follow all of the creators of this podcast`,
defaultValue: false
}
},
outputFields: () => ({
viewer: {
type: types.PersonType,
resolve: payload => payload.person
},
podcast: {
type: types.PodcastType,
resolve: async payload => await new db.Podcast({id: payload.podcastId}).fetch()
}
}),
mutateAndGetPayload: requireAuthMutation(async ({ podcastId, autofollowCreators }, {person, loaders}) => {
try {
var {id} = fromGlobalId(podcastId);
log.info(pre+`person ${person.id} is subscribing to podcast ${podcastId} (${id})`);
const podcast = await loaders.podcast.load(id);
assert(podcast, `The podcast you are trying to subscribe to does not exist`);
// Subscribe to the podcast
await person.subscribeToPodcast(id, true);
// Join the community for this podcast
await person.joinCommunityForPodcast(id);
// If specified, autofollow all of the creators of this podcast
// This means that the new listener joined via a branch link
if (autofollowCreators) {
const credits = await podcast.credits();
log.info(pre+`autofollowing ${credits.length} credited users`);
await Promise.map(credits.models, async (credit) => {
// Try to follow this person
try {
const creator = await loaders.person.load(credit.get('person'));
// Do the follow
await person.follow(creator.id, true);
// Send a "creator notification"
await actions.listenerJoined(person, creator, podcast);
} catch(e) {
log.error(`Error following person: `, e);
}
});
}
return { person, podcastId: id };
} catch(e) {
log.error('Error subscribing to podcast: ', e);
throw new GraphQLError('Error subscribing to podcast.');
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment