Skip to content

Commit d82405c

Browse files
📝 Add docstrings to feat/bootstrap-scripts
Docstrings generation was requested by @0xkenj1. * #63 (comment) The following files were modified: * `packages/shared/src/utils/testing.ts` * `scripts/bootstrap/src/schemas/index.ts` * `scripts/migrations/src/migrations/external-services-cache/20250127T000000_add_cache_tables.ts` * `scripts/migrations/src/migrations/processing/20241029T120000_initial.ts` * `scripts/migrations/src/utils/kysely.ts`
1 parent 37c63ae commit d82405c

File tree

5 files changed

+126
-14
lines changed

5 files changed

+126
-14
lines changed

packages/shared/src/utils/testing.ts

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,42 @@ export function mergeDeep<T extends ObjectType>(target: T, source: DeepPartial<T
3434
}
3535

3636
/**
37-
* Type guard to check if a value is an object
38-
* @param item The value to check
39-
* @returns True if the value is an object, false otherwise
37+
* Determines whether the provided value is a non-null object that is not an array.
38+
*
39+
* This type guard checks that the value is of type "object", is not null, and explicitly excludes arrays.
40+
* It is useful for ensuring a value conforms to an object shape before performing object-specific operations.
41+
*
42+
* @param item - The value to check.
43+
* @returns True if `item` is a non-null object and not an array; otherwise, false.
44+
*
45+
* @example
46+
* ```typescript
47+
* const value: unknown = { key: 'value' };
48+
* if (isObject(value)) {
49+
* // Within this block, TypeScript treats `value` as an object.
50+
* }
51+
* ```
4052
*/
4153
function isObject(item: unknown): item is ObjectType {
4254
return item !== null && typeof item === "object" && !Array.isArray(item);
4355
}
4456

57+
/**
58+
* Determines whether the provided value can be parsed as a valid JSON string.
59+
*
60+
* This function attempts to parse the input as a JSON string. If parsing is successful,
61+
* it returns `true` (indicating that the input conforms to JSON structure and is thus considered a valid JSON object).
62+
* If parsing fails, it logs the error to the console and returns `false`.
63+
*
64+
* @param item - The value to test for valid JSON structure.
65+
* @returns `true` if the input can be successfully parsed as JSON; otherwise, `false`.
66+
*
67+
* @example
68+
* const jsonString = '{"name": "Alice", "age": 30}';
69+
* if (isJSON(jsonString)) {
70+
* // jsonString is a valid JSON and now inferred to be of ObjectType
71+
* }
72+
*/
4573
export function isJSON(item: unknown): item is ObjectType {
4674
try {
4775
JSON.parse(item as string);

scripts/bootstrap/src/schemas/index.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,17 @@ const env = validationSchema.safeParse(process.env);
5353

5454
export type DbEnvConfig = z.infer<typeof dbEnvSchema>;
5555

56+
/**
57+
* Retrieves the validated database configuration from environment variables.
58+
*
59+
* This function uses the `dbEnvSchema` to safely parse and validate the environment variables
60+
* provided in `process.env`. If the validation fails, it logs a detailed error message and throws
61+
* an exception to halt further execution. On successful validation, it returns the configuration
62+
* structured as defined by `DbEnvConfig`.
63+
*
64+
* @returns The validated database configuration.
65+
* @throws Error when the environment variables do not conform to the expected schema.
66+
*/
5667
export function getDatabaseConfigFromEnv(): DbEnvConfig {
5768
const result = dbEnvSchema.safeParse(process.env);
5869

@@ -64,6 +75,16 @@ export function getDatabaseConfigFromEnv(): DbEnvConfig {
6475
return result.data;
6576
}
6677

78+
/**
79+
* Retrieves validated environment variables.
80+
*
81+
* This function checks whether the environment variables have been successfully validated using `validationSchema`.
82+
* If the validation fails, it logs the formatted error details and throws an exception to prevent further execution
83+
* with invalid configurations. On successful validation, it returns the structured environment settings.
84+
*
85+
* @returns The validated environment variables conforming to `validationSchema`.
86+
* @throws Error if the environment variables do not pass validation.
87+
*/
6788
export function getEnv(): z.infer<typeof validationSchema> {
6889
if (!env.success) {
6990
console.error("❌ Invalid environment variables:", env.error.format());

scripts/migrations/src/migrations/external-services-cache/20250127T000000_add_cache_tables.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,26 @@
11
import { Kysely, sql } from "kysely";
22

3+
/**
4+
* Executes the "up" migration to create caching tables in the database.
5+
*
6+
* This function creates two tables:
7+
*
8+
* - **priceCache**: Stores pricing data with the following columns:
9+
* - `tokenCode` (text): Not nullable.
10+
* - `timestampMs` (bigint): Not nullable.
11+
* - `priceUsd` (decimal(36, 18)): Not nullable.
12+
* - `createdAt` (timestamptz): Defaults to the current timestamp.
13+
* A composite primary key is defined on `tokenCode` and `timestampMs`.
14+
*
15+
* - **metadataCache**: Stores metadata with the following columns:
16+
* - `id` (text): Not nullable.
17+
* - `metadata` (jsonb): Nullable, allowing null values.
18+
* - `createdAt` (timestamptz): Defaults to the current timestamp.
19+
* A primary key is defined on the `id` column.
20+
*
21+
* @param db - The Kysely database instance used to execute the migration queries.
22+
* @returns A promise that resolves when the migration is complete.
23+
*/
324
export async function up(db: Kysely<unknown>): Promise<void> {
425
// Create pricing cache table
526
await db.schema

scripts/migrations/src/migrations/processing/20241029T120000_initial.ts

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,31 @@ import { getSchemaName } from "../../utils/index.js";
77
* The only argument for the functions is an instance of Kysely<any>. It's important to use Kysely<any> and not Kysely<YourDatabase>.
88
* ref: https://kysely.dev/docs/migrations#migration-files
99
*/
10-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
10+
/**
11+
* Applies the database schema upgrade migration using the Kysely schema builder.
12+
*
13+
* This function performs a series of asynchronous schema modifications to support new application features.
14+
* It creates custom enum types, tables, indexes, foreign key constraints, and a SQL function for project search.
15+
*
16+
* Schema changes include:
17+
* - Creating the "project_type" enum type with values "canonical" and "linked".
18+
* - Creating the "projects" table with various columns and a primary key constraint on (id, chainId), along with an index on metadata.
19+
* - Creating tables for pending and confirmed project roles, including the "pending_project_roles" and "project_roles" tables.
20+
* - Creating the "rounds" table with multiple columns for managing rounds and associated indexes for performance.
21+
* - Creating tables for pending and confirmed round roles, including the "pending_round_roles" and "round_roles" tables.
22+
* - Creating the "application_status" enum type and the "applications" table with foreign key constraints to projects and rounds.
23+
* - Creating the "applications_payouts" table with a foreign key linking to applications.
24+
* - Creating the "donations" table with corresponding indexes for optimized queries.
25+
* - Creating the "legacy_projects" table for legacy project data.
26+
* - Defining a custom SQL function for project search.
27+
*
28+
* @param db - The Kysely database instance used to execute the schema migration commands. The database's schema
29+
* property is used to dynamically reference qualified table names.
30+
*
31+
* @returns A promise that resolves once the schema migration is successfully applied.
32+
*
33+
* @throws An error if any of the schema creation or alteration commands fail.
34+
*/
1135
export async function up(db: Kysely<any>): Promise<void> {
1236
const BIGINT_TYPE = sql`decimal(78,0)`;
1337
const ADDRESS_TYPE = "text";

scripts/migrations/src/utils/kysely.ts

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,23 @@ export const getSchemaName = (schema: SchemaModule): string => {
3232
};
3333

3434
/**
35-
* Applies all migrations to the database up to the latest version.
35+
* Applies all available migrations to the database up to the latest version.
3636
*
37-
* @param config - The migration configuration.
38-
* @param config.db - The Kysely database instance.
39-
* @param config.schema - The schema to use for the migrations. Should be the same as the schema used in the Kysely database instance.
40-
* @returns The migration results.
37+
* This function ensures that the specified schema exists and then uses file-based migrations to update the
38+
* database. It creates a migrator using the provided database instance and migration configurations, including
39+
* dynamically constructed migration table names based on the given domain. Each migration's status is logged,
40+
* and in case of an error during the migration process, the error is logged and re-thrown.
41+
*
42+
* @param config - The migration configuration object.
43+
* @param config.db - The Kysely database instance used to execute migration queries.
44+
* @param config.schema - The name of the schema to apply migrations, which should match the database schema.
45+
* @param config.migrationsFolder - The folder path containing migration files.
46+
* @param config.domain - The domain string used to dynamically name the migration tables.
47+
* @param logger - The logger instance for logging migration statuses and errors.
48+
*
49+
* @returns A promise that resolves to an array of migration result objects if migrations are applied, or undefined otherwise.
50+
*
51+
* @throws If an error occurs during the migration process, the error is logged and thrown.
4152
*/
4253
export async function migrateToLatest<T>(
4354
config: MigrationConfig<T>,
@@ -77,12 +88,19 @@ export async function migrateToLatest<T>(
7788
}
7889

7990
/**
80-
* Resets the database by rolling back all migrations.
91+
* Resets the database by rolling back all applied migrations.
92+
*
93+
* This function initializes a Migrator with a file migration provider and reverts the database
94+
* state by rolling back all migrations. The migration and lock table names are dynamically constructed
95+
* using the provided domain (formatted as "<domain>_migrations" and "<domain>_migrations_lock").
8196
*
82-
* @param config - The migration configuration.
83-
* @param config.db - The Kysely database instance.
84-
* @param config.schema - The schema to use for the migrations. Should be the same as the schema used in the Kysely database instance.
85-
* @returns The migration results.
97+
* @param config - The migration configuration, including:
98+
* - db: The Kysely database instance.
99+
* - migrationsFolder: The folder path containing migration files.
100+
* - domain: The domain used to namespace the migration tables.
101+
* @param logger - The logger instance for recording migration events and errors.
102+
* @returns A promise that resolves to an array of migration results if successful, or undefined.
103+
* @throws Will throw an error if the migration reset process encounters an issue.
86104
*/
87105
export async function resetDatabase<T>(
88106
config: MigrationConfig<T>,

0 commit comments

Comments
 (0)