All files / apps / api/src / server / channel service.ts

100% Statements 22/22
100% Branches 14/14
100% Functions 4/4
100% Lines 20/20

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                                                29x     9x       32x                                       39x 39x 39x 6x     33x 33x   28x 28x                       28x 28x       5x   1x     23x                                       27x               27x 27x   27x            
import {
  CHANNEL_ERROR_CODE,
  ERROR_CODE,
  fold,
  type Channel,
  type ChannelBrowseQuery,
  type ChannelPage,
  type CreateChannelRequest,
} from '@chattra/shared'
import { mainDb } from '../../db/client'
import { newId } from '../../lib/id'
import { ApiHttpError } from '../http'
import { canCreateChannel, type Actor } from '../permission/service'
import {
  browseChannels as findChannels,
  createChannel as insertChannel,
  findMemberCreate,
  isChannelNameTaken,
  type ChannelRow,
} from './repository'
 
// Create and browse channels (design 5.1, tickets #18 and #20).
 
const NAME_INDEX_CLASH =
  'UNIQUE constraint failed: conversations.workspace_id, conversations.name_norm'
 
function nameTaken(name: string): ApiHttpError {
  return new ApiHttpError(CHANNEL_ERROR_CODE.nameTaken, `#${name} already exists`)
}
 
function toChannel(row: ChannelRow): Channel {
  return {
    id: row.id,
    name: row.name,
    kind: row.kind,
    topic: row.topic,
    description: row.description,
    isGeneral: row.isGeneral,
    archivedAt: row.archivedAt,
    memberCount: row.memberCount,
    joined: row.joined,
    createdAt: row.createdAt,
  }
}
 
/** POST /api/channels (#18): the creator becomes its first member, as admin. */
export async function createChannel(
  env: Env,
  actor: Actor,
  input: CreateChannelRequest,
): Promise<Channel> {
  const db = mainDb(env)
  const memberCreate = await findMemberCreate(db, actor.workspaceId)
  if (!memberCreate || !canCreateChannel(actor, input.kind, memberCreate)) {
    throw new ApiHttpError(ERROR_CODE.forbidden, 'You cannot create this kind of channel')
  }
 
  const nameNorm = fold(input.name)
  if (await isChannelNameTaken(db, actor.workspaceId, nameNorm)) throw nameTaken(input.name)
 
  const now = Date.now()
  const channel = {
    id: newId(now),
    messageId: newId(now),
    workspaceId: actor.workspaceId,
    kind: input.kind,
    name: input.name,
    nameNorm,
    description: input.description?.trim() || null,
    createdBy: actor.userId,
    createdAt: now,
  }
 
  try {
    await insertChannel(db, channel)
  } catch (error) {
    // Two creates of one name at once both pass the check above; the unique index decides, and the
    // loser gets the same answer as a name that was already taken.
    if (String(error).includes(NAME_INDEX_CLASH)) throw nameTaken(input.name)
 
    throw error
  }
 
  return {
    id: channel.id,
    name: channel.name,
    kind: channel.kind,
    topic: null,
    description: channel.description,
    isGeneral: false,
    archivedAt: null,
    memberCount: 1,
    joined: true,
    createdAt: now,
  }
}
 
/** GET /api/channels/browse (#20): cursor-paged by folded name, with the total of the filter. */
export async function browseChannels(
  env: Env,
  actor: Actor,
  query: ChannelBrowseQuery,
): Promise<ChannelPage> {
  const { rows, total } = await findChannels(mainDb(env), {
    workspaceId: actor.workspaceId,
    userId: actor.userId,
    scope: query.scope,
    type: query.type,
    limit: query.limit + 1,
    cursor: query.cursor,
  })
  const page = rows.slice(0, query.limit)
  const last = page.at(-1)
 
  return {
    channels: page.map(toChannel),
    nextCursor: last && rows.length > query.limit ? last.nameNorm : null,
    total,
  }
}