From 9277a804bbfdd1aa5dfc5edfe4fe5207b732ee33 Mon Sep 17 00:00:00 2001 From: Alan Bridgeman Date: Mon, 17 Feb 2025 16:19:35 -0600 Subject: [PATCH] Initial commit --- .gitignore | 16 ++++ Dockerfile | 26 ++++++ README.md | 57 ++++++++++++ gulpfile.mjs | 42 +++++++++ package.json | 34 ++++++++ src/entity/Chart.ts | 33 +++++++ src/pages/base.ejs | 145 +++++++++++++++++++++++++++++++ src/pages/includes/footer.ejs | 0 src/pages/includes/header.ejs | 0 src/pages/index.ejs | 13 +++ src/routes/HarborRoutes.ts | 61 +++++++++++++ src/routes/HelmRoutes.ts | 63 ++++++++++++++ src/routes/HomeRoutes.ts | 9 ++ src/server.ts | 39 +++++++++ src/static/css/accessibility.css | 28 ++++++ src/static/css/style.css | 87 +++++++++++++++++++ src/utils/db.ts | 82 +++++++++++++++++ tsconfig.json | 116 +++++++++++++++++++++++++ 18 files changed, 851 insertions(+) create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 gulpfile.mjs create mode 100644 package.json create mode 100644 src/entity/Chart.ts create mode 100644 src/pages/base.ejs create mode 100644 src/pages/includes/footer.ejs create mode 100644 src/pages/includes/header.ejs create mode 100644 src/pages/index.ejs create mode 100644 src/routes/HarborRoutes.ts create mode 100644 src/routes/HelmRoutes.ts create mode 100644 src/routes/HomeRoutes.ts create mode 100644 src/server.ts create mode 100644 src/static/css/accessibility.css create mode 100644 src/static/css/style.css create mode 100644 src/utils/db.ts create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f8df668 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +# Ignore Yarn files +.yarn +.yarnrc.yml +yarn.lock + +# Ignore dependencies +node_modules + +# Ignore private NPM credentials +.npmrc + +# Mac OS +.DS_Store + +# Ignore compiled files +dist \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..01b2565 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +FROM node:lts + +WORKDIR /usr/src/app + +COPY package*.json ./ +COPY .npmrc ./ +COPY yarn.lock ./ + +RUN yarn install --frozen-lockfile + +COPY ./src ./src +COPY ./gulpfile.mjs ./ +COPY ./tsconfig.json ./ + +RUN yarn build + +ARG NODE_ENV=production +ENV NODE_ENV=$NODE_ENV + +ARG PORT=3000 +ENV PORT=$PORT + +EXPOSE $PORT + +CMD ["yarn", "start"] + diff --git a/README.md b/README.md new file mode 100644 index 0000000..1dd30dd --- /dev/null +++ b/README.md @@ -0,0 +1,57 @@ +# Harbor Helm Index +The Harbor Helm Index software was designed for one very specific purpose. To expose Helm charts hosted in Harbor as if it was a Helm native repository. More specifically, to be able to use an easier to remember human oriented name for charts rather than a URI. + +## Getting Started +There are a few different ways you can run the software +- [using Helm (**Recommended**)](#helm-chart) +- [using Docker](#docker) +- [using Node](#node) + +### Helm Chart +As you might imagine for a tool that is intended to work with Helm the easiest way to deploy it is to use helm (yes, by doing this, you would be making use of this software) + +```console +helm repo add BridgemanAccessible https://helm.bridgemanaccessible.ca/ +helm install my-helm-index BridgemanAccessibe/harbor-helm-index +``` + +### Docker +You could deploy the docker container locally. However, this would involve being a lot more explicit about environment variables. + +```console +docker run --name my-helm-index \ + --env NODE_ENV=development \ + --env PORT=8080 \ + --env COMPANY="My Company" \ + --env WEBSITE_TITLE_SUFFIX=" - My Company Helm Repo" \ + --env HOSTNAME="helm.exmaple.com" \ + --env DB_HOST="postgres.db.example.com" \ + --env DB_NAME=harbor_helm_index \ + --env DB_PASSWORD="Pa55w0rd!" \ + --env DB_PORT=5432 \ + --env DB_USER=helm_index \ + --env CACHE_HOSTNAME="redis.example.com" \ + --env CACHE_PORT=6379 \ + --env CACHE_PASSWORD="Pa55w0rd!" \ + harbor-helm-image +``` + +### Node +You could run it with Node by running `yarn start`. However, similar to Docker you would need to figure out a way to inject the needed environment variables. + +## How It Works +There are two primary parts to how the software works. + +The [Harbor](https://goharbor.io) part which involves receiving information about Helm charts as their uploaded or deleted from the registry. + +The [Helm](https://helm.sh) part which involves exposing a specific `index.yaml` file for the Helm CLI to consume. + +The following subsections will go into this in more details + +### Harbor Webhooks +Luckily, Harbor offers us an easy and efficient way to have an event driven architecture as it relates to getting information about uploaded and deleted charts. More specifically, this is done through the use of webhooks which allows Harbor to send a notifying request to an endpoint exposed by this software. + +The endpoint configured is `/harbor`. + +### Helm's `index.yaml` +Helm's `repo` commands requires that the repository exposes a `index.yaml` file at it's root about the available charts. This is generated automatically by this software. \ No newline at end of file diff --git a/gulpfile.mjs b/gulpfile.mjs new file mode 100644 index 0000000..0b9549f --- /dev/null +++ b/gulpfile.mjs @@ -0,0 +1,42 @@ +import gulp from "gulp"; +import ts from "gulp-typescript"; +import { deleteAsync } from 'del'; + +var tsProject = ts.createProject("tsconfig.json"); + +// Task which would delete the old dist directory if present +gulp.task("build-clean", function () { + return deleteAsync(["./dist"]); +}); + +// Task which would transpile typescript to javascript +gulp.task("typescript", function () { + return tsProject.src().pipe(tsProject()).js.pipe(gulp.dest("dist")); +}); + +// Task which would just create a copy of the current views directory in dist directory +gulp.task("views", function () { + return gulp.src("./src/pages/**/*.ejs").pipe(gulp.dest("./dist/pages")); +}); + +// Task which will copy the assets from the static JavaScript directory to the dist directory +gulp.task("assets-js", function () { + return gulp.src(['./src/static/js/**/*.js']).pipe(gulp.dest("./dist/static/js")); +}); + +// Task which will copy the assets from the static image directory to the dist directory +gulp.task("assets-img", function () { + return gulp.src("./src/static/img/**/*", { encoding: false }).pipe(gulp.dest("./dist/static/img")); +}); + +// Task which will copy the assets from the static CSS directory to the dist directory +gulp.task("assets-css", function () { + return gulp.src("./src/static/css/**/*.css").pipe(gulp.dest("./dist/static/css")); +}); + +gulp.task("assets", gulp.parallel("assets-js", "assets-img", "assets-css")); + +// The default task which runs at start of the gulpfile.js +gulp.task("default", gulp.series("build-clean", "typescript", "views", "assets"), () => { + console.log("Done"); +}); \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..12d9f99 --- /dev/null +++ b/package.json @@ -0,0 +1,34 @@ +{ + "name": "harbor-helm-index", + "version": "1.0.0", + "description": "An app to generate and server a Helm repo index.yaml for a set of OCI based Helm charts stored in Harbor", + "main": "index.js", + "repository": "https://github.com/AlanBridgeman/harbor-helm-index", + "author": "Alan Bridgeman ", + "license": "MIT", + "scripts": { + "build": "gulp", + "start": "node dist/server.js" + }, + "devDependencies": { + "@types/ejs": "^3.1.5", + "@types/express": "^5.0.0", + "@types/gulp": "^4.0.17", + "@types/js-yaml": "^4.0.9", + "@types/node": "^22.13.4", + "del": "^8.0.0", + "gulp": "^5.0.0", + "gulp-typescript": "^6.0.0-alpha.1", + "typescript": "^5.7.3" + }, + "dependencies": { + "@BridgemanAccessible/ba-web-framework": "^1.0.0", + "ejs": "^3.1.10", + "express": "^4.21.2", + "js-yaml": "^4.1.0", + "pg": "^8.13.3", + "typeorm": "^0.3.20", + "uuid": "^11.0.5" + }, + "packageManager": "yarn@1.22.22" +} diff --git a/src/entity/Chart.ts b/src/entity/Chart.ts new file mode 100644 index 0000000..536a098 --- /dev/null +++ b/src/entity/Chart.ts @@ -0,0 +1,33 @@ +import { Entity, BaseEntity, PrimaryColumn, Column, OneToMany, ManyToOne, Relation } from 'typeorm'; + +/** Represents a Helm Chart */ +@Entity("Charts") +export class Chart extends BaseEntity { + /** The unique ID of the Helm Chart */ + @PrimaryColumn() + id!: string; + + /** When the Helm Chart was pushed/created */ + @Column() + created!: Date; + + /** The user that pushed the Helm Chart (operator from Harbor webhook) */ + @Column() + user!: string; + + /** Helm Chart Name */ + @Column() + name!: string; + + /** Helm chart digest */ + @Column() + digest!: string; + + /** Helm chart tag */ + @Column() + tag!: string; + + /** Helm Chart URL */ + @Column() + url!: string; +} \ No newline at end of file diff --git a/src/pages/base.ejs b/src/pages/base.ejs new file mode 100644 index 0000000..fa5faba --- /dev/null +++ b/src/pages/base.ejs @@ -0,0 +1,145 @@ + + + + + <% if(typeof description !== 'undefined') { %> + <%# If the description is explicitly set use it %> + + <% } else if(typeof company !== 'undefined') { %> + <%# If the description isn't explicitly set but the company name is (company variable) then assume this a generic company Helm chart repository and set the description as such %> + + <% } %> + <% if (typeof keywords !== 'undefined') { %> + <%# If the keywords are explicitly set use them %> + + <% } else { %> + <%# If the keywords aren't explicitly set then use the default keywords %> + + <% } %> + <% if (typeof author !== 'undefined') { %> + <%# If the author is explicitly set use it %> + + <% } else if (typeof company !== 'undefined') { %> + <%# If the author isn't explicitly set but the company name is (company variable) then use it as the author %> + + <% } %> + + <% if(typeof title !== 'undefined' && title.length > 0) { %> + <% if (typeof titlePrefix !== 'undefined') { %><%= titlePrefix %><% } %><%= title %><% if (typeof titleSuffix !== 'undefined') { %><%= titleSuffix %><% } %> + <% } %> + + + + + <%# %> + <%# %> + <%# %> + <%# %> + + <%# Add any additional stylesheets specified within a controller etc... %> + <%# This can either be a singular string or a array of strings %> + <%# Note, that the string should be the name of the stylesheet WITHOUT the `.css` extension and exist in the `css/` directory %> + <% if (typeof extraStyles !== 'undefined') { %> + <% if (Array.isArray(extraStyles)) { %> + <%# Because it's an array, we need to loop through each stylesheet and include it %> + <% for (let style of extraStyles) { %> + + <% } %> + <% } else { %> + <%# Include the singular stylesheet %> + + <% } %> + <% } %> + + + <%# %> + <%# %> + <%# %> + <%# %> + + <%# Add any additional scripts specified within a controller etc... %> + <%# %> + <%# Note, that these can come in multiple formats as described in the table below: %> + <%# | Type | Description | Format | Use Cases | %> + <%# | ------ | --------------------------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------- | %> + <%# | string | The name of the script to include | ` + <% } else { %> + <%# Because the `.script` property doesn't start with `http` or `https` we assume it's a "local" script and include it as a local script (from the `js/` folder and with a `.js` extension) %> + + <% } %> + <% } else { %> + <% if(script.startsWith('http') || script.startsWith('https')) { %> + <%# Because the string starts with `http` or `https` we assume it's an "external" script and include it as a straight URL %> + + <% } else { %> + <%# Because the string doesn't start with `http` or `https` we assume it's a "local" script and include it as a local script (from the `js/` folder and with a `.js` extension) %> + + <% } %> + <% } %> + <% } %> + <% } else if (typeof extraScripts === 'object') { %> + <% if(extraScripts.script.startsWith('http') || extraScripts.script.startsWith('https')) { %> + <%# Because the `.script` property of the singular object starts with `http` or `https` we assume it's an "external" script and include it as a straight URL %> + + <% } else { %> + <%# Because the `.script` property of the singular object doesn't start with `http` or `https` we assume it's a "local" script and include it as a local script (from the `js/` folder and with a `.js` extension) %> + + <% } %> + <% } else { %> + <% if(extraScripts.startsWith('http') || extraScripts.startsWith('https')) { %> + <%# Because the singular string starts with `http` or `https` we assume it's an "external" script and include it as a straight URL %> + + <% } else { %> + <%# Because the singular string doesn't start with `http` or `https` we assume it's a "local" script and include it as a local script (from the `js/` folder and with a `.js` extension) %> + + <% } %> + <% } %> + <% } %> + + + +
+
+ <% if(typeof header !== 'undefined') { %> + <%# Because the controller has explicitly set the header, we use the specified header here (within the `
` tags) %> + <%- include(header) %> + <% } else { %> + <%# Because no explicitly header was set use the default header %> + <%- include('includes/header.ejs') %> + <% } %> +
+
+
+
+
+ <%- include(page) %> +
+
+
+
+ <% if(typeof footer !== 'undefined') { %> + <%# Because the controller has explicitly set the footer, we use the specified footer here (within the `
` tags) %> + <%- include(footer) %> + <% } else { %> + <%# Because no explicitly footer was set use the default footer %> + <%- include('includes/footer.ejs') %> + <% } %> +
+
+
+ + \ No newline at end of file diff --git a/src/pages/includes/footer.ejs b/src/pages/includes/footer.ejs new file mode 100644 index 0000000..e69de29 diff --git a/src/pages/includes/header.ejs b/src/pages/includes/header.ejs new file mode 100644 index 0000000..e69de29 diff --git a/src/pages/index.ejs b/src/pages/index.ejs new file mode 100644 index 0000000..951a5c5 --- /dev/null +++ b/src/pages/index.ejs @@ -0,0 +1,13 @@ +

Welcome to the <%= company %> Helm Repository

+

+ To use this repository, you need to add it to your Helm client. +

+
helm repo add <%= company.replaceAll(' ', '') %> https://<%= hostname %>/
+

+ Once you have added the repository, you can search for charts in the repository. +

+
helm search repo <%= company.replaceAll(' ', '') %>
+

+ To install a chart from the repository, use the following command. +

+
helm install my-release <%= company.replaceAll(' ', '') %>/some-chart
\ No newline at end of file diff --git a/src/routes/HarborRoutes.ts b/src/routes/HarborRoutes.ts new file mode 100644 index 0000000..d7a9914 --- /dev/null +++ b/src/routes/HarborRoutes.ts @@ -0,0 +1,61 @@ +import express, { Request, Response } from 'express'; +import { v4 as newUUID } from 'uuid'; +import { Controller, POST, BaseController } from '@BridgemanAccessible/ba-web-framework'; + +import { Chart } from '../entity/Chart'; + +type WebhookResponse = { + type: 'PUSH_ARTIFACT' | 'DELETE_ARTIFACT', + occur_at: number, + operator: string, + event_data: { + resources: { + digest: string, + tag: string, + resource_url: string + }[], + repository: { + date_created?: number, + name: string, + namespace: string, + repo_full_name: string, + repo_type: string + } + } +}; + +@Controller() +export class HarborRoutes extends BaseController { + @POST('/harbor', express.json()) + async webhook(req: Request, res: Response) { + const response: WebhookResponse = req.body; + if(response.type === 'PUSH_ARTIFACT') { + console.log('Pushed a new Helm Chart'); + + // Create a new database entry for the Helm Chart that got pushed + await Chart.create({ + id: newUUID(), + created: new Date(response.occur_at), + user: response.operator, + name: response.event_data.repository.name, + digest: response.event_data.resources[0].digest, + tag: response.event_data.resources[0].tag, + url: response.event_data.resources[0].resource_url + }).save(); + } + else if(response.type === 'DELETE_ARTIFACT') { + console.log('Deleted a Helm Chart'); + + // Delete the Helm Chart from the database + Chart.delete({ digest: response.event_data.resources[0].digest }); + } + console.log(`Happened At: ${response.occur_at}`); + console.log(`User (Operator): ${response.operator}`); + console.log(`Name: ${response.event_data.repository.name}`); + console.log(`Digest: ${response.event_data.resources[0].digest}`); + console.log(`Tag: ${response.event_data.resources[0].tag}`); + console.log(`URL: ${response.event_data.resources[0].resource_url}`); + + res.status(200).send('ok'); + } +} \ No newline at end of file diff --git a/src/routes/HelmRoutes.ts b/src/routes/HelmRoutes.ts new file mode 100644 index 0000000..4b6d040 --- /dev/null +++ b/src/routes/HelmRoutes.ts @@ -0,0 +1,63 @@ +import { Request, Response } from 'express'; +import { Controller, GET, BaseController } from '@BridgemanAccessible/ba-web-framework'; +import { dump as writeYAML } from 'js-yaml'; + +import { Chart } from '../entity/Chart'; + +type HelmRepoIndexEntry = { + apiVersion: 'v1', + appVersion: `${string}.${string}.${string}`, + dependencies: { + name: string, + repository: string, + version: `${string}.${string}.${string}` + }[], + description: string, + digest: string, + home: string, + name: string, + sources: string[], + urls: string[], + version: `${string}.${string}.${string}` +}; + +type HelmRepoIndex = { + apiVersion: 'v1', + entries: { + [key: string]: HelmRepoIndexEntry[] + } +}; + +@Controller() +export class HelmRoutes extends BaseController { + @GET('/index.yaml') + private async index(req: Request, res: Response) { + const index: HelmRepoIndex = { + apiVersion: 'v1', + entries: {} + }; + + // Get all Helm Charts from the database and add them to the index + const charts = await Chart.find(); + charts.forEach(chart => { + index.entries[chart.name] = [ + { + apiVersion: 'v1', + appVersion: '1.0.0', + dependencies: [], + description: chart.name, + digest: chart.digest, + home: `https://${process.env.HOSTNAME}/${chart.url.substring(chart.url.indexOf('/', chart.url.indexOf('/') + 1) + 1, chart.url.indexOf(':'))}`, + name: chart.name, + sources: [], + urls: [`oci://${chart.url}`], + version: chart.tag as `${string}.${string}.${string}` + } + ]; + }) + + res.status(200) + .setHeader('Content-Type', 'application/yaml') // Per IANA Media Types listing as noted in [RFC 9512](https://datatracker.ietf.org/doc/html/rfc9512) + .send(writeYAML(index)); + } +} \ No newline at end of file diff --git a/src/routes/HomeRoutes.ts b/src/routes/HomeRoutes.ts new file mode 100644 index 0000000..94c1f52 --- /dev/null +++ b/src/routes/HomeRoutes.ts @@ -0,0 +1,9 @@ +import { Request, Response } from 'express'; +import { Controller, GET, Page, BaseController } from '@BridgemanAccessible/ba-web-framework'; + +@Controller() +export class HomeRoutes extends BaseController { + @Page('Home', 'index.ejs') + @GET('/') + async home(req: Request, res: Response) {} +} \ No newline at end of file diff --git a/src/server.ts b/src/server.ts new file mode 100644 index 0000000..d751551 --- /dev/null +++ b/src/server.ts @@ -0,0 +1,39 @@ +import path from 'path'; +import { Application } from 'express'; +import { App, Initializer, globalTemplateValues } from '@BridgemanAccessible/ba-web-framework'; + +import { createConn } from './utils/db'; + +/** + * Create the initial database connection + * + * This includes setting up the connection options and creating the connection itself. + */ +async function createInitialDatabaseConnection() { + // Setup the database connection options + const connOptions = { + synchronize: process.env.NODE_ENV !== 'production', + logging: process.env.NODE_ENV !== 'production' + } + + // Create a connection to the database + await createConn('postgres', connOptions); +} + +async function onStart(app: Application) { + // Create the initial database connection + createInitialDatabaseConnection(); +} + +async function main() { + await new App().run(new Initializer({ + controllersPath: path.join(__dirname, 'routes'), + staticFilesPath: path.join(__dirname, 'static'), + view: { + engine: 'ejs', + filesPath: path.join(__dirname, 'pages') + } + }, globalTemplateValues({ company: process.env.COMPANY, titleSuffix: process.env.WEBSITE_TITLE_SUFFIX, hostname: process.env.HOSTNAME })), onStart); +} + +main() \ No newline at end of file diff --git a/src/static/css/accessibility.css b/src/static/css/accessibility.css new file mode 100644 index 0000000..12f3da3 --- /dev/null +++ b/src/static/css/accessibility.css @@ -0,0 +1,28 @@ +/* Style for the "skip to content" link found at the top of the page */ +#skip-link { + position: absolute; + top: -40px; + left: 0; + background: #fff; + color: #000; + padding: 8px; + z-index: 100; + height: 0; +} + +/* Style to visually show the "skip to content" link when keyboard has focus */ +#skip-link:focus { + top: 0; + height: auto; +} + +/* For elements that should be hidden visually bt NOT from screen readers */ +/* Ex. input form labels that are labeled differently visually */ +.visually-hidden { + position: absolute; + height: 1px; + width: 1px; + overflow: hidden; + clip: rect(1px, 1px, 1px, 1px); + white-space: nowrap; +} \ No newline at end of file diff --git a/src/static/css/style.css b/src/static/css/style.css new file mode 100644 index 0000000..4ca05f5 --- /dev/null +++ b/src/static/css/style.css @@ -0,0 +1,87 @@ +:root { + min-height: 100%; +} + +html, body { + position: relative; + width: 100%; + min-height: 100%; + margin: 0; + padding: 0; + /*font-family: 'Arial', sans-serif; + font-size: 14pt; + color: #000; + background-color: #fff; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale;*/ +} + +main { + min-height: 100%; + padding-top: 5px; + padding-left: 10px; + padding-right: 10px; + padding-bottom: 60px; +} + +.hidden { + display: none; + visibility: hidden; +} + +/*#contents { + display: flex; + flex-direction: row; +} + +#contents #sidebar { + display: flex; + flex-direction: column; + width: 384px; + min-height: 100vh; + background-color: #C2C2C2; + padding: 20px; +} + +#contents #sidebar button:hover { + cursor: pointer; +} + +#contents #sidebar button:hover, +#contents #sidebar button:focus, +#contents #sidebar a:hover, +#contents #sidebar a:focus { + background-color: #000000; + color: #FFFFFF; +} + +#contents #sidebar hr { + background-color: #000000; + width: 100%; + height: 1px; +} + +#contents main { + display: flex; + flex-direction: column; + flex-grow: 1; + padding: 20px; +} + +.btn { + display: inline-block; + padding: 10px 20px; + background-color: #C2C2C2; + color: #000000; + text-decoration: none; + text-align: center; + border-radius: 5px; + border: 1px solid #000000; +} + +.btn-panel { + display: flex; + flex-direction: row; + justify-content: space-between; + margin-bottom: 20px; +}*/ \ No newline at end of file diff --git a/src/utils/db.ts b/src/utils/db.ts new file mode 100644 index 0000000..e05d613 --- /dev/null +++ b/src/utils/db.ts @@ -0,0 +1,82 @@ +import path from 'path'; +import { DataSource } from 'typeorm'; + +/** + * Creates a connection to the database. + * + * @param kwargs Other keyword arguments to pass to the TypeORM DataSource. (ex. { logging: true }) + * @returns A connection to the database. + */ +async function createPostgreSQLConn(kwargs: object): Promise { + // Parse the database connection information from the environment variables + const DB_HOST = process.env.DB_HOST; + const DB_PORT: number = typeof process.env.DB_PORT !== 'undefined' ? parseInt(process.env.DB_PORT) : 5432; + const DB_USER = process.env.DB_USER || 'postgres'; + const DB_PASSWORD = process.env.DB_PASSWORD || 'db_password'; + const DB_NAME = process.env.DB_NAME || 'db'; + + console.log(`Attempting to connect to ${DB_HOST} at port ${DB_PORT} on database ${DB_NAME} as ${DB_USER} with password ${DB_PASSWORD}`); + + // Create the connection + return new DataSource({ + type: "postgres", + host: DB_HOST, + port: DB_PORT, + username: DB_USER, + password: DB_PASSWORD, + database: DB_NAME, + //ssl: process.env.NODE_ENV === 'production' ? true : false, + ...kwargs, + entities: [ + path.resolve(__dirname, '../', './entity/**/*.ts'), + path.resolve(__dirname, '../', './entity/**/*.js') + ] + }).initialize(); +} + +/** + * Creates a connection to the SQLite database. + * + * @param kwargs Other keyword arguments to pass to the TypeORM DataSource. (ex. { logging: true }) + * @returns The connection to the database. + */ +async function createSQLiteConn(kwargs: object): Promise { + // Parse the database connection information from the environment variables + const DB_NAME = process.env.DATABASE_FILE || 'database.sqlite'; + + console.log(`Attempting to connect to ${DB_NAME}`); + + // Create the connection + return new DataSource({ + type: "sqlite", + database: DB_NAME, + ...kwargs, + entities: [ + path.resolve(__dirname, '../', './entity/**/*.ts'), + path.resolve(__dirname, '../', './entity/**/*.js') + ] + }).initialize(); +} + +/** + * The types of databases that can be connected to. + */ +type DBTypes = 'sqlite' | 'postgres'; + +/** + * Creates a connection to the database. + * + * @param kwargs The keyword arguments to pass to the TypeORM DataSource. (ex. { logging: true }) + * @returns The connection to the database. + */ +export async function createConn(dbType: DBTypes, kwargs: object): Promise { + // Return the connection based on the database type + switch(dbType) { + case 'sqlite': + return createSQLiteConn(kwargs); + break; + case 'postgres': + return createPostgreSQLConn(kwargs); + break; + } +} \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..e73fd9b --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,116 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "ES2024", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + "lib": [ "DOM", "ES2022", "ESNext.AsyncIterable" ], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + "rootDir": "src", /* Specify the root folder within your source files. */ + "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + "baseUrl": ".", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "noUncheckedSideEffectImports": true, /* Check side effect imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./dist", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ + "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + "strictPropertyInitialization": false, /* Check for class properties that are declared but not set in the constructor. */ + // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ "node_modules" ], + "include": [ + "./src/**/*.tsx", + "./src/**/*.ts" + ] +}