<commit_before><commit_msg>Step 7.6: Create logic.js<commit_after>import { ApolloError, AuthenticationError, ForbiddenError } from 'apollo-server';
import { Message } from './connectors';

// reusable function to check for a user with context
function getAuthenticatedUser(ctx) {
  return ctx.user.then((user) => {
    if (!user) {
      throw new AuthenticationError('Unauthenticated');
    }
    return user;
  });
}

export const messageLogic = {
  createMessage(_, { text, groupId }, ctx) {
    return getAuthenticatedUser(ctx)
      .then(user => user.getGroups({ where: { id: groupId }, attributes: ['id'] })
        .then((group) => {
          if (group.length) {
            return Message.create({
              userId: user.id,
              text,
              groupId,
            });
          }
          throw new ForbiddenError('Unauthorized');
        }));
  },
};

{'fraction_non_alphanumeric': 0.1347678369195923, 'fraction_numerical': 0.0022650056625141564, 'mean_word_length': 2.453125, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3058593', 'n_tokens_mistral': 257, 'n_tokens_neox': 254, 'n_words': 61}