Initial commit

This commit is contained in:
Alan Bridgeman 2025-02-17 16:19:35 -06:00
commit 9277a804bb
18 changed files with 851 additions and 0 deletions

16
.gitignore vendored Normal file
View file

@ -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

26
Dockerfile Normal file
View file

@ -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"]

57
README.md Normal file
View file

@ -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.

42
gulpfile.mjs Normal file
View file

@ -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");
});

34
package.json Normal file
View file

@ -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 <a.bridgeman@hotmail.com>",
"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"
}

33
src/entity/Chart.ts Normal file
View file

@ -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;
}

145
src/pages/base.ejs Normal file
View file

@ -0,0 +1,145 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<% if(typeof description !== 'undefined') { %>
<%# If the description is explicitly set use it %>
<meta name="description" content="<%= description %>">
<% } 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 %>
<meta name="description" content="<% if(typeof company !== 'undefined') { %><%= company %> <% } %> Helm Repository">
<% } %>
<% if (typeof keywords !== 'undefined') { %>
<%# If the keywords are explicitly set use them %>
<meta name="keywords" content="<%= keywords %>">
<% } else { %>
<%# If the keywords aren't explicitly set then use the default keywords %>
<meta name="keywords" content="helm, kubernetes, repository, charts, <% if(typeof company !== 'undefined') { %><%= company %> <% } %>">
<% } %>
<% if (typeof author !== 'undefined') { %>
<%# If the author is explicitly set use it %>
<meta name="author" content="<%= author %>">
<% } 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 %>
<meta name="author" content="<%= company %>">
<% } %>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<% if(typeof title !== 'undefined' && title.length > 0) { %>
<title><% if (typeof titlePrefix !== 'undefined') { %><%= titlePrefix %><% } %><%= title %><% if (typeof titleSuffix !== 'undefined') { %><%= titleSuffix %><% } %></title>
<% } %>
<!-- Styles -->
<!-- Custom styling -->
<link rel="stylesheet" type="text/css" href="/css/style.css">
<link rel="stylesheet" type="text/css" href="/css/accessibility.css">
<%# <!-- Foundation Framework --> %>
<%# <link rel="stylesheet" href="/css/app.css"> %>
<%# <!-- SASS components --> %>
<%# <link rel="stylesheet" type="text/css" href="/css/components/system-themed-background.css"> %>
<!-- Controller specific styling -->
<%# 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) { %>
<link rel="stylesheet" type="text/css" href="/css/<%= style %>.css">
<% } %>
<% } else { %>
<%# Include the singular stylesheet %>
<link rel="stylesheet" type="text/css" href="/css/<%= extraStyles %>.css">
<% } %>
<% } %>
<!-- Scripts -->
<!-- Third-party scripts -->
<%# <script src="https://js.stripe.com/v3" async></script> %>
<%# <script src="https://kit.fontawesome.com/c754d91c7e.js" crossorigin="anonymous"></script> %>
<%# <!-- Foundation Framework --> %>
<%# <script type="application/javascript" src="/js/foundation/main.js" defer></script> %>
<!-- Controller specific scripts -->
<%# 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 | `<script name>` | Simple include of the script | %>
<%# | object | An object about the script to include | `{ script: '<script name>', defer: <true/false> }` | Being more explicit about script's properties (ex. defer vs. async, etc...) | %>
<%# | array | An array of strings or objects (as described above) | `[ '<script name>', { script: '<script name>', defer: <true/false> } ]` | Include multiple scripts | %>
<%# %>
<%# The string or `.script` property of the object should be the script name WITHOUT the `.js` extension and exist in the `js/` directory if it's a "local" script. %>
<%# Or should be the full URL if it's a "external" script %>
<% if (typeof extraScripts !== 'undefined') { %>
<% if (Array.isArray(extraScripts)) { %>
<%# Because it's an array, we need to loop through each script and include it %>
<% for (let script of extraScripts) { %>
<% if(typeof script === 'object') { %>
<%# Because the current array items is an object we use the `.script` and `.defer` properties to include it %>
<% if(script.script.startsWith('http') || script.script.startsWith('https')) { %>
<%# Because the `.script` property starts with `http` or `https` we assume it's an "external" script and include it as a straight URL %>
<script type="application/javascript" src="<%= script.script %>" <% if(script.defer) { %>defer<% } %>></script>
<% } 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) %>
<script type="application/javascript" src="/js/<%= script.script %>.js" <% if(script.defer) { %>defer<% } %>></script>
<% } %>
<% } 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 %>
<script type="application/javascript" src="<%= script %>"></script>
<% } 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) %>
<script type="application/javascript" src="/js/<%= script %>.js" defer></script>
<% } %>
<% } %>
<% } %>
<% } 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 %>
<script type="application/javascript" src="<%= extraScripts.script %>" <% if(extraScripts.defer) { %>defer<% } %>></script>
<% } 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) %>
<script type="application/javascript" src="/js/<%= extraScripts.script %>.js" <% if(extraScripts.defer) { %>defer<% } %>></script>
<% } %>
<% } 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 %>
<script type="application/javascript" src="<%= extraScripts %>"></script>
<% } 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) %>
<script type="application/javascript" src="/js/<%= extraScripts %>.js" defer></script>
<% } %>
<% } %>
<% } %>
</head>
<body>
<a id="skip-link" href="#main">Skip to main content</a>
<div id="contents">
<header>
<% if(typeof header !== 'undefined') { %>
<%# Because the controller has explicitly set the header, we use the specified header here (within the `<header></header>` tags) %>
<%- include(header) %>
<% } else { %>
<%# Because no explicitly header was set use the default header %>
<%- include('includes/header.ejs') %>
<% } %>
</header>
<div style="width: 100%">
<main id="main">
<div class="container">
<div class="content">
<%- include(page) %>
</div>
</div>
</main>
<footer>
<% if(typeof footer !== 'undefined') { %>
<%# Because the controller has explicitly set the footer, we use the specified footer here (within the `<footer></footer>` tags) %>
<%- include(footer) %>
<% } else { %>
<%# Because no explicitly footer was set use the default footer %>
<%- include('includes/footer.ejs') %>
<% } %>
</footer>
</div>
</div>
</body>
</html>

View file

View file

13
src/pages/index.ejs Normal file
View file

@ -0,0 +1,13 @@
<h1>Welcome to the <%= company %> Helm Repository</h1>
<p>
To use this repository, you need to add it to your Helm client.
</p>
<pre>helm repo add <%= company.replaceAll(' ', '') %> https://<%= hostname %>/</pre>
<p>
Once you have added the repository, you can search for charts in the repository.
</p>
<pre>helm search repo <%= company.replaceAll(' ', '') %></pre>
<p>
To install a chart from the repository, use the following command.
</p>
<pre>helm install my-release <%= company.replaceAll(' ', '') %>/some-chart</pre>

View file

@ -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');
}
}

63
src/routes/HelmRoutes.ts Normal file
View file

@ -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));
}
}

9
src/routes/HomeRoutes.ts Normal file
View file

@ -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) {}
}

39
src/server.ts Normal file
View file

@ -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()

View file

@ -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;
}

87
src/static/css/style.css Normal file
View file

@ -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;
}*/

82
src/utils/db.ts Normal file
View file

@ -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<DataSource> {
// 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<DataSource> {
// 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<DataSource> {
// Return the connection based on the database type
switch(dbType) {
case 'sqlite':
return createSQLiteConn(kwargs);
break;
case 'postgres':
return createPostgreSQLConn(kwargs);
break;
}
}

116
tsconfig.json Normal file
View file

@ -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 '<reference>'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"
]
}