All files / app/models/invite invite-repository.ts

100% Statements 32/32
90.91% Branches 20/22
100% Functions 7/7
100% Lines 32/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 2631x 1x   1x 1x 1x                                                       1x                 1x         1x             1x                                                                                 1x                       9x   9x   9x                 9x 5x 5x   4x                         5x     5x   5x                                     3x   3x                                   2x 2x   2x                                   4x 4x                                         3x   3x                                               8x 8x               8x      
import {User, Group, Invite} from '@models';
import {InviteNotFoundError} from '@errors';
import {RepositoryQueryOptions} from 'typings';
import {buildFindQueryOptionsMethod} from '@app/util/build-find-query-options';
import debug from 'debug';
import {containsTransaction, isTransaction} from '@util/is-transaction';
 
export type InviteId = {userId: number, groupId: number};
 
/**
 * Options of find queries
 */
export interface FindOptions extends RepositoryQueryOptions {
  [key: string]: unknown;
 
  /**
   * Whether the group data should be returned instead of the groupId
   */
  withGroupData: boolean;
  /**
   * Whether the user data should be returned instead of the userId
   */
  withUserData: boolean;
  /**
   * Whether the invitedBy field
   * should include the user data instead of the id
   */
  withInvitedByData: boolean;
}
 
/**
 * Default find options
 */
const defaultFindOptions: FindOptions = {
  withGroupData: false,
  withUserData: false,
  withInvitedByData: false,
};
 
/**
 * Method for logging.
 */
const log = debug('group-car:invite:repository');
 
/**
 * Method for error logging.
 */
const error = debug('group-car:invite:repository:error');
 
/**
 * Builds the array of models to include
 * in the query from {@link FindOptions}.
 * @param options - The options which define the to included models.
 */
const buildOptions = buildFindQueryOptionsMethod(
    [
      {
        key: 'withGroupData',
        include: [{
          model: Group,
          as: 'Group',
          attributes: Group.simpleAttributes,
          include: [{
            model: User,
            as: 'Owner',
            attributes: User.simpleAttributes,
          }],
        }],
      },
      {
        key: 'withUserData',
        include: [{
          model: User,
          as: 'User',
          attributes: User.simpleAttributes,
        }],
      },
      {
        key: 'withInvitedByData',
        include: [{
          model: User,
          as: 'InviteSender',
          attributes: User.simpleAttributes,
        }],
      },
    ],
    defaultFindOptions,
);
 
/**
 * Repository for invites.
 *
 * Provides an abstraction and security layer
 * over the model.
 */
export const InviteRepository = {
 
  /**
   * Returns the invite with the given id.
   * If no invite exists will throw {@link InviteNotFoundError}.
   * @param id          - The id of the invite, consists of user and group id
   * @param options     - FindOptions define what should be eagerly loaded
   */
  async findById(
      id: InviteId,
      options?: Partial<FindOptions>,
  ): Promise<Invite> {
    log('Find invite of user %d for group %d', id.userId, id.groupId);
    // Prepare the include array
    const {include} = buildOptions(options);
 
    const invite = await Invite.findOne({
      where: {
        userId: id.userId,
        groupId: id.groupId,
      },
      include,
      transaction: isTransaction(options?.transaction),
    });
 
    if (invite === null) {
      error('No invite of user %d for group %d exists', id.userId, id.groupId);
      throw new InviteNotFoundError(id);
    } else {
      return invite;
    }
  },
 
  /**
   * Returns a list of all invites the user has.
   * @param userId          - The currently logged-in user
   * @param options       - FindOptions define what should be eagerly loaded
   */
  async findAllForUser(
      userId: number,
      options?: Partial<FindOptions>,
  ): Promise<Invite[]> {
    log('Find all invites for user %d', userId);
 
    // Prepare the include array
    const {include} = buildOptions(options);
 
    return Invite.findAll({
      where: {
        userId,
      },
      include,
      transaction: isTransaction(options?.transaction),
    });
  },
 
  /**
   * Deletes an invite which is for the given user and group.
   * @param id - ID of the invite
   * @param options - Options
   * @returns Promise of number of deleted rows
   */
  async deleteById(
      id: InviteId,
      options?: RepositoryQueryOptions,
  ): Promise<number> {
    log('Delete invite of user %d for group %d', id.userId, id.groupId);
 
    return Invite.destroy({
      where: {
        userId: id.userId,
        groupId: id.groupId,
      },
      transaction: isTransaction(options?.transaction),
    });
  },
 
  /**
   * Gets all invites for the specified group.
   * @param groupId - The if of the group
   * @param options - Query options
   */
  async findAllForGroup(
      groupId: number,
      options?: Partial<FindOptions>,
  ): Promise<Invite[]> {
    log('Find all invites for group %d', groupId, options);
    const {include} = buildOptions(options);
 
    return Invite.findAll({
      where: {
        groupId,
      },
      include,
    });
  },
 
  /**
   * Gets the amount of invites of a group.
   * @param groupId - ID of the group
   * @param options - Additional options
   * @returns Amount of invites for the given group as a Promise
   */
  async countForGroup(
      groupId: number,
      options?: Partial<RepositoryQueryOptions>,
  ): Promise<number> {
    log('Cound invites for group %d', groupId);
    return Invite.count({
      where: {
        groupId,
      },
      transaction: isTransaction(options?.transaction),
    });
  },
 
  /**
   * Creates an invite for the given id.
   * @param userId    - ID of the user to invite
   * @param groupId   - ID of the group
   * @param invitedBy - ID of the user which created the invite
   * @param options - Additional options
   */
  async create(
      userId: number,
      groupId: number,
      invitedBy: number,
      options?: Partial<RepositoryQueryOptions>,
  ): Promise<Invite> {
    log('Create new invite for user %d and group %d', userId, groupId);
 
    return Invite.create(
        {
          userId,
          groupId,
          invitedBy,
        }, {
          ...containsTransaction(options),
        },
    );
  },
 
  /**
   * Checks if the invite with the given id exists.
   *
   * This is basically equivalent to checking if the user
   * is invited to the group.
   * @param groupId - ID of the user
   * @param userId  - ID of the group
   * @param options - Additional options
   */
  async exists(
      {groupId, userId}: InviteId,
      options?: Partial<RepositoryQueryOptions>,
  ): Promise<boolean> {
    log('Check if invite for user %d and group %d exists', userId, groupId);
    const invite = await Invite.findOne({
      where: {
        groupId,
        userId,
      },
      transaction: isTransaction(options?.transaction),
    });
 
    return invite !== null;
  },
};