-
Notifications
You must be signed in to change notification settings - Fork 0
Add documentation support and SQL execution #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
abdotop
wants to merge
2
commits into
master
Choose a base branch
from
5-add-documentation-support-and-sql-execution
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import { APP_ENV, DEVTOOL_ACCESS_TOKEN } from '@01edu/api/env' | ||
| import { respond } from '@01edu/api/response' | ||
| import type { RequestContext } from '@01edu/types/context' | ||
| import { route } from '@01edu/api/router' | ||
| import { ARR, OBJ, optional, STR } from '@01edu/api/validator' | ||
| import type { Sql } from '@01edu/db' | ||
|
|
||
| /** | ||
| * Authorizes access to developer routes. | ||
| * Checks for `DEVTOOL_ACCESS_TOKEN` in the Authorization header. | ||
| * In non-prod environments, access is allowed if no token is configured. | ||
| * | ||
| * @param ctx - The request context. | ||
| * @throws {respond.UnauthorizedError} If access is denied. | ||
| */ | ||
| export const authorizeDevAccess = ({ req }: RequestContext) => { | ||
| if (APP_ENV !== 'prod') return // always open for dev env | ||
| const auth = req.headers.get('Authorization') || '' | ||
| const bearer = auth.toLowerCase().startsWith('bearer ') | ||
| ? auth.slice(7).trim() | ||
| : '' | ||
| if (bearer && bearer === DEVTOOL_ACCESS_TOKEN) return | ||
| throw new respond.UnauthorizedError({ message: 'Unauthorized access' }) | ||
| } | ||
|
|
||
| /** | ||
| * Creates a route handler for executing arbitrary SQL queries. | ||
| * Useful for debugging and development tools. | ||
| * | ||
| * @param sql - The SQL tag function to use for execution. | ||
| * @returns A route handler configuration. | ||
| */ | ||
| export const createSqlDevRoute = (sql?: Sql) => { | ||
| return route({ | ||
| authorize: authorizeDevAccess, | ||
| fn: (_, { query, params }) => { | ||
| try { | ||
| if (!sql) { | ||
| return respond.NotImplemented({ | ||
| message: 'Database not configured', | ||
| }) | ||
| } | ||
| return sql`${query}`.all(params) | ||
| } catch (error) { | ||
| throw new respond.BadRequestError({ | ||
| message: error instanceof Error ? error.message : 'Unexpected Error', | ||
| }) | ||
| } | ||
| }, | ||
| input: OBJ({ | ||
| query: STR('The SQL query to execute'), | ||
| params: optional(OBJ({}, 'The parameters to bind to the query')), | ||
abdotop marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }), | ||
| output: ARR( | ||
| optional(OBJ({}, 'A single result row')), | ||
| 'List of results', | ||
| ), | ||
| description: 'Execute an SQL query', | ||
| }) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| import type { Def, DefBase } from '@01edu/types/validator' | ||
| import type { GenericRoutes } from '@01edu/types/router' | ||
| import { route } from '@01edu/api/router' | ||
| import { ARR, BOOL, LIST, OBJ, optional, STR } from '@01edu/api/validator' | ||
|
|
||
| /** | ||
| * Recursive type representing the structure of input/output documentation. | ||
| * It mirrors the structure of the validator definitions but simplified for documentation purposes. | ||
| */ | ||
| export type Documentation = | ||
| & ( | ||
| | { type: Exclude<DefBase['type'], 'object' | 'array' | 'list' | 'union'> } | ||
| | { type: 'object'; properties: Record<string, Documentation> } | ||
| | { type: 'array'; items: Documentation } | ||
| | { type: 'list'; options: (string | number)[] } | ||
| | { type: 'union'; options: Documentation[] } | ||
| ) | ||
| & { description?: string; optional?: boolean } | ||
|
|
||
| /** | ||
| * Represents the documentation for a single API endpoint. | ||
| */ | ||
| export type EndpointDoc = { | ||
| method: string | ||
| path: string | ||
| requiresAuth: boolean | ||
| authFunction: string | ||
| description?: string | ||
| input?: Documentation | ||
| output?: Documentation | ||
| } | ||
|
|
||
| /** | ||
| * Extracts documentation from a validator definition. | ||
| * Recursively processes objects and arrays to build a `Documentation` structure. | ||
| * | ||
| * @param def - The validator definition to extract documentation from. | ||
| * @returns The extracted documentation or undefined if no definition is provided. | ||
| */ | ||
| function extractDocs(def?: Def): Documentation | undefined { | ||
| if (!def) return undefined | ||
| const base = { | ||
| type: def.type, | ||
| description: def.description, | ||
| optional: def.optional, | ||
| } | ||
|
|
||
| switch (def.type) { | ||
| case 'object': { | ||
| const properties: Record<string, Documentation> = {} | ||
| for (const [key, value] of Object.entries(def.properties)) { | ||
| const doc = extractDocs(value) | ||
| if (doc) { | ||
| properties[key] = doc | ||
| } | ||
| } | ||
| return { ...base, properties, type: 'object' } | ||
| } | ||
| case 'array': { | ||
| const items = extractDocs(def.of) as Documentation | ||
| return { ...base, items, type: 'array' } | ||
| } | ||
| case 'list': | ||
| return { ...base, options: def.of as (string | number)[], type: 'list' } | ||
| case 'union': | ||
| return { | ||
| ...base, | ||
| options: def.of.map((d: Def) => extractDocs(d) as Documentation), | ||
| type: 'union', | ||
| } | ||
| case 'boolean': | ||
| return { ...base, type: 'boolean' } | ||
| case 'number': | ||
| return { ...base, type: 'number' } | ||
| case 'string': | ||
| return { ...base, type: 'string' } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Generates API documentation for a set of routes. | ||
| * Iterates through the route definitions and extracts metadata, input, and output documentation. | ||
| * | ||
| * @param defs - The route definitions to generate documentation for. | ||
| * @returns An array of `EndpointDoc` objects describing the API. | ||
| */ | ||
| export const generateApiDocs = (defs: GenericRoutes) => { | ||
| return Object.entries<typeof defs[keyof typeof defs]>(defs).map( | ||
| ([key, handler]) => { | ||
| const slashIndex = key.indexOf('/') | ||
| const method = key.slice(0, slashIndex).toUpperCase() | ||
| const path = key.slice(slashIndex) | ||
| const requiresAuth = handler.authorize ? true : false | ||
abdotop marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return { | ||
| method, | ||
| path, | ||
| requiresAuth, | ||
| authFunction: handler.authorize?.name || '', | ||
| description: 'description' in handler ? handler.description : undefined, | ||
| input: 'input' in handler ? extractDocs(handler.input) : undefined, | ||
| output: 'output' in handler ? extractDocs(handler.output) : undefined, | ||
| } | ||
| }, | ||
| ) | ||
| } | ||
|
|
||
| const encoder = new TextEncoder() | ||
| const apiDocOutputDef: Def = ARR( | ||
| OBJ({ | ||
| method: LIST(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], 'HTTP method'), | ||
| path: STR('API endpoint path'), | ||
| requiresAuth: BOOL('whether authentication is required'), | ||
| authFunction: STR('name of the authorization function'), | ||
| description: STR('Endpoint description'), | ||
| input: optional(OBJ({}, 'Input documentation structure')), | ||
| output: optional(OBJ({}, 'Output documentation structure')), | ||
| }, 'API documentation object structure'), | ||
| 'API documentation array', | ||
| ) | ||
|
|
||
| /** | ||
| * Creates a route handler that serves the generated API documentation. | ||
| * The documentation is served as a JSON array of `EndpointDoc` objects. | ||
| * | ||
| * @param defs - The route definitions to generate documentation for. | ||
| * @returns A route handler that serves the API documentation. | ||
| */ | ||
| export const createDocRoute = (defs: GenericRoutes) => { | ||
| const docStr = JSON.stringify(generateApiDocs(defs)) | ||
| const docBuffer = encoder.encode(docStr) | ||
| return route({ | ||
| fn: () => | ||
| new Response(docBuffer, { | ||
| headers: { 'content-type': 'application/json' }, | ||
| }), | ||
| output: apiDocOutputDef, | ||
| description: 'Get the API documentation', | ||
| }) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.