| 1 | // SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | |
| 3 | package orgs |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "errors" |
| 8 | |
| 9 | "github.com/jackc/pgx/v5" |
| 10 | "github.com/jackc/pgx/v5/pgxpool" |
| 11 | |
| 12 | orgsdb "github.com/tenseleyFlow/shithub/internal/orgs/sqlc" |
| 13 | ) |
| 14 | |
| 15 | // PrincipalKind discriminates the resolution result. |
| 16 | type PrincipalKind string |
| 17 | |
| 18 | const ( |
| 19 | PrincipalUser PrincipalKind = "user" |
| 20 | PrincipalOrg PrincipalKind = "org" |
| 21 | ) |
| 22 | |
| 23 | // Principal is the resolution result. ID is the user_id when Kind is |
| 24 | // "user", org_id when "org". |
| 25 | type Principal struct { |
| 26 | Slug string |
| 27 | Kind PrincipalKind |
| 28 | ID int64 |
| 29 | } |
| 30 | |
| 31 | // ErrNoPrincipal is returned when /{slug} doesn't match a known |
| 32 | // principal. Web handlers translate this to 404. |
| 33 | var ErrNoPrincipal = errors.New("orgs: no principal for slug") |
| 34 | |
| 35 | // Resolve answers the central /{slug} routing question with one |
| 36 | // indexed lookup. Returns ErrNoPrincipal for unknown slugs (handler |
| 37 | // 404s); other errors are surfaced as-is. |
| 38 | func Resolve(ctx context.Context, pool *pgxpool.Pool, slug string) (Principal, error) { |
| 39 | row, err := orgsdb.New().ResolvePrincipal(ctx, pool, slug) |
| 40 | if err != nil { |
| 41 | if errors.Is(err, pgx.ErrNoRows) { |
| 42 | return Principal{}, ErrNoPrincipal |
| 43 | } |
| 44 | return Principal{}, err |
| 45 | } |
| 46 | return Principal{ |
| 47 | Slug: string(row.Slug), |
| 48 | Kind: PrincipalKind(row.Kind), |
| 49 | ID: row.ID, |
| 50 | }, nil |
| 51 | } |
| 52 |