| 1 | import { |
| 2 | ownerNameOf, |
| 3 | type RepositoryOperation, |
| 4 | } from '../repositories/access/repository-access.js'; |
| 5 | import { AuthenticationRequiredError } |
| 6 | import { RepositoryNotFoundError } |
| 7 | import type { RepositoryAccessService |
| 8 | import { DomainError } |
| 9 | import { CouldNotResolveError } |
| 10 | |
| 11 | /** The access check, with "can't see it" in GitHub's words: anonymous and stranger reads of a private repository both read as missing. */ |
| 12 | export async function authorizeOrNotFound |
| 13 | access: RepositoryAccessService |
| 14 | { |
| 15 | owner, |
| 16 | name, |
| 17 | requesterId, |
| 18 | operation, |
| 19 | }: { |
| 20 | owner: string |
| 21 | name: string |
| 22 | requesterId?: string |
| 23 | operation?: RepositoryOperation |
| 24 | }, |
| 25 | ) { |
| 26 | try { |
| 27 | return await access |
| 28 | username: owner, |
| 29 | repo: name, |
| 30 | requesterId, |
| 31 | operation, |
| 32 | }); |
| 33 | } catch (error) |
| 34 | if ( |
| 35 | error instanceof RepositoryNotFoundError |
| 36 | error instanceof AuthenticationRequiredError |
| 37 | ) { |
| 38 | throw new CouldNotResolveError( |
| 39 | `Could not resolve to a Repository with the name '${owner}/${ |
| 40 | ); |
| 41 | } |
| 42 | throw error; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | /** Whether an error means the viewer cannot see the thing (401) or it is not there (404), both of which GitHub answers as "could not resolve". */ |
| 47 | export function isUnresolvable(error |
| 48 | return ( |
| 49 | error instanceof DomainError |
| 50 | (error.status === |
| 51 | ); |
| 52 | } |
| 53 | |
| 54 | /** The promise's value, or null when it fails as unresolvable; any other failure, such as the database being down, propagates. */ |
| 55 | export function orNull<T |
| 56 | return promise.catch |
| 57 | if (isUnresolvable(error |
| 58 | throw error; |
| 59 | }); |
| 60 | } |