| 1 | import { type Database, schema } from '@ghost/db'; |
| 2 | import { Inject, Injectable |
| 3 | import { and, asc |
| 4 | |
| 5 | import { DATABASE } |
| 6 | import { RepositoryAccessService } |
| 7 | import { escapeLike } |
| 8 | |
| 9 | const LIMIT = 8 |
| 10 | |
| 11 | type SuggestionRef |
| 12 | username: string |
| 13 | repo: string |
| 14 | requesterId?: string |
| 15 | q?: string |
| 16 | }; |
| 17 | |
| 18 | /** What the Markdown editor and the assignee picker offer as someone types `@`, `#` or a name. */ |
| 19 | @Injectable() |
| 20 | export class SuggestionsService |
| 21 | constructor( |
| 22 | @Inject(DATABASE) |
| 23 | private readonly access |
| 24 | ) {} |
| 25 | |
| 26 | /** People whose username starts with `q`, those involved in the repository first. With nothing typed, only the involved: its owner, collaborators, organization members and everyone who opened or commented on an issue in it. */ |
| 27 | async users({ |
| 28 | const repository = |
| 29 | const involved = |
| 30 | select ${repository.ownerId}::text |
| 31 | union select user_id from repository_collaborator where repository_id = ${repository.id} and accepted_at is not null |
| 32 | union select user_id from member where organization_id = ${repository.organizationId} |
| 33 | union select author_id from issue where repository_id = ${repository.id} |
| 34 | union select c.author_id from issue_comment c join issue i on i.id = c.issue_id where i.repository_id = ${repository.id} |
| 35 | )`; |
| 36 | const prefix = |
| 37 | |
| 38 | const users = |
| 39 | .select({ |
| 40 | username: sql<string |
| 41 | name: schema.user |
| 42 | image: schema.user |
| 43 | }) |
| 44 | .from(schema.user |
| 45 | .where( |
| 46 | and( |
| 47 | isNotNull(schema.user |
| 48 | prefix |
| 49 | ? ilike(schema. |
| 50 | : involved, |
| 51 | ), |
| 52 | ) |
| 53 | .orderBy(desc(involved |
| 54 | .limit(LIMIT); |
| 55 | return { users |
| 56 | } |
| 57 | |
| 58 | /** Issues and pull requests whose number starts with `q`, or whose title contains it; newest first. */ |
| 59 | async issues({ |
| 60 | const repository = |
| 61 | const query = |
| 62 | |
| 63 | const issues = |
| 64 | .select({ |
| 65 | number: schema.issue |
| 66 | title: schema.issue |
| 67 | state: schema.issue |
| 68 | isPullRequest: schema.issue |
| 69 | }) |
| 70 | .from(schema.issue |
| 71 | .where( |
| 72 | and( |
| 73 | eq(schema.issue |
| 74 | !query |
| 75 | ? undefined |
| 76 | : /^\d+$/. |
| 77 | ? sql`${schema |
| 78 | : ilike(schema. |
| 79 | ), |
| 80 | ) |
| 81 | .orderBy(desc(schema |
| 82 | .limit(LIMIT); |
| 83 | return { issues |
| 84 | } |
| 85 | } |