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

100% Statements 18/18
91.66% Branches 11/12
100% Functions 5/5
100% Lines 16/16

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                                                              41x           41x                 37x           37x                                 32x   32x                                                                                                                                   87x 71x   38x                       87x                 87x         87x           87x 87x   87x                                             87x    
import type {
  ChannelBrowseScope,
  ChannelBrowseType,
  ChannelKind,
  MemberCreate,
} from '@chattra/shared'
import {
  and,
  asc,
  count,
  eq,
  exists,
  gt,
  isNotNull,
  isNull,
  ne,
  notExists,
  or,
  sql,
} from 'drizzle-orm'
import type { SQL } from 'drizzle-orm'
import type { DrizzleD1Database } from 'drizzle-orm/d1'
import { conversationMembers, conversations, events, messages, workspaces } from '../../db/schema'
 
// Channels: create and browse (design 3.1, 5.1). Times are integer ms.
 
/** Which channels a Member may create in this workspace; undefined when the workspace is unknown. */
export async function findMemberCreate(
  db: DrizzleD1Database,
  workspaceId: string,
): Promise<MemberCreate | undefined> {
  const [row] = await db
    .select({ memberCreate: workspaces.memberCreate })
    .from(workspaces)
    .where(eq(workspaces.id, workspaceId))
    .limit(1)
 
  return row?.memberCreate
}
 
/** Whether any channel of the workspace, archived ones included, already has this folded name. */
export async function isChannelNameTaken(
  db: DrizzleD1Database,
  workspaceId: string,
  nameNorm: string,
): Promise<boolean> {
  const [row] = await db
    .select({ id: conversations.id })
    .from(conversations)
    .where(and(eq(conversations.workspaceId, workspaceId), eq(conversations.nameNorm, nameNorm)))
    .limit(1)
 
  return row !== undefined
}
 
export interface NewChannel {
  id: string
  messageId: string
  workspaceId: string
  kind: ChannelKind
  name: string
  nameNorm: string
  description: string | null
  createdBy: string
  createdAt: number
}
 
/** The channel, its first admin, the "created this channel" message and their events in one batch (design 3.1, 4.4). */
export async function createChannel(db: DrizzleD1Database, channel: NewChannel): Promise<void> {
  const { id, messageId, createdBy, createdAt } = channel
 
  await db.batch([
    db.insert(conversations).values({
      id,
      workspaceId: channel.workspaceId,
      kind: channel.kind,
      name: channel.name,
      nameNorm: channel.nameNorm,
      description: channel.description,
      lastMessageSeq: 1,
      lastVisibleSeq: 1,
      createdBy,
      createdAt,
    }),
    db
      .insert(conversationMembers)
      .values({ conversationId: id, userId: createdBy, role: 'admin', joinedAt: createdAt }),
    db.insert(messages).values({
      id: messageId,
      conversationId: id,
      seq: 1,
      authorId: createdBy,
      kind: 'system',
      body: 'created this channel',
      createdAt,
    }),
    db.insert(events).values({
      conversationId: id,
      type: 'message.created',
      payload: JSON.stringify({ v: 1, messageId }),
      createdAt,
    }),
    db.insert(events).values({
      userId: createdBy,
      conversationId: id,
      type: 'member.added',
      payload: JSON.stringify({ v: 1, memberIds: [createdBy] }),
      createdAt,
    }),
  ])
}
 
export interface BrowseChannelsInput {
  workspaceId: string
  userId: string
  scope: ChannelBrowseScope
  type: ChannelBrowseType
  /** Rows to read; the service asks for one more than the page to know whether another follows. */
  limit: number
  cursor?: string
}
 
export interface ChannelRow {
  id: string
  name: string
  nameNorm: string
  kind: ChannelKind
  topic: string | null
  description: string | null
  isGeneral: boolean
  archivedAt: number | null
  createdAt: number
  memberCount: number
  joined: boolean
}
 
function typeFilter(type: BrowseChannelsInput['type']): SQL | undefined {
  if (type === 'archived') return isNotNull(conversations.archivedAt)
  if (type === 'any') return isNull(conversations.archivedAt)
 
  return and(eq(conversations.kind, type), isNull(conversations.archivedAt))
}
 
/**
 * One page of the channels this person may see, by folded name, and the total of the same filter.
 * Visibility is not an option: never a DM, never another workspace, and a private channel only to
 * its members, whatever the role (design 2.5).
 */
export async function browseChannels(
  db: DrizzleD1Database,
  { workspaceId, userId, scope, type, limit, cursor }: BrowseChannelsInput,
): Promise<{ rows: ChannelRow[]; total: number }> {
  const membership = db
    .select({ one: sql`1` })
    .from(conversationMembers)
    .where(
      and(
        eq(conversationMembers.conversationId, conversations.id),
        eq(conversationMembers.userId, userId),
      ),
    )
  const memberCount = db
    .select({ count: count() })
    .from(conversationMembers)
    .where(eq(conversationMembers.conversationId, conversations.id))
 
  const visible = and(
    ne(conversations.kind, 'dm'),
    eq(conversations.workspaceId, workspaceId),
    or(eq(conversations.kind, 'public'), exists(membership)),
  )
  const scopeFilter =
    scope === 'mine' ? exists(membership) : scope === 'other' ? notExists(membership) : undefined
  const filters = and(visible, scopeFilter, typeFilter(type))
 
  const [rows, [totalRow]] = await db.batch([
    db
      .select({
        id: conversations.id,
        // conversations_name_norm_check makes both names non-null for every kind but dm.
        name: sql<string>`coalesce(${conversations.name}, ${conversations.nameNorm})`,
        nameNorm: sql<string>`${conversations.nameNorm}`,
        kind: sql<ChannelKind>`${conversations.kind}`,
        topic: conversations.topic,
        description: conversations.description,
        isGeneral: sql<boolean>`${conversations.isGeneral}`.mapWith(Boolean),
        archivedAt: conversations.archivedAt,
        createdAt: conversations.createdAt,
        memberCount: sql<number>`${memberCount}`,
        joined: sql<boolean>`${exists(membership)}`.mapWith(Boolean),
      })
      .from(conversations)
      .where(and(filters, cursor ? gt(conversations.nameNorm, cursor) : undefined))
      .orderBy(asc(conversations.nameNorm))
      .limit(limit),
    db.select({ total: count() }).from(conversations).where(filters),
  ])
 
  return { rows, total: totalRow?.total ?? 0 }
}