Boilerplate generator and deno tasks for monorepo

This commit is contained in:
Emma
2023-05-01 20:28:18 -06:00
parent a367562ba0
commit a910783882
36 changed files with 1164 additions and 47 deletions

30
lib/Application.ts Normal file
View File

@@ -0,0 +1,30 @@
import { Application, Router } from 'oak';
import { authenticateUser } from 'middleware/auth.ts';
type servicePrefix = `/${string}`;
interface IServiceOpts {
prefix: servicePrefix;
}
export class CGGService<T> extends Application<T & {user?: string}> {
public prefix: servicePrefix;
constructor(options: IServiceOpts) {
super();
this.prefix = options.prefix;
this.use(authenticateUser);
// this.baseRouter = new Router({prefix: this.prefix});
}
start() {
const port = Deno.args.at(0);
this.listen({ port: port ? Number(port) : undefined })
}
route(router: Router) {
router.prefix(this.prefix);
this.use(router.routes())
this.use(router.allowedMethods());
}
}

16
lib/data.ts Normal file
View File

@@ -0,0 +1,16 @@
import mongoose from 'mongoose';
import { vault } from 'common/vault.ts';
/**
*
* @param dbName The Database to open
*/
export const configDatabase = async (mg: typeof mongoose, dbName = 'BattleLog') => {
if (!vault.get('MONGODB_URI')) throw 'No MongoDB URI, is your secrets file present and populated?'
await mg.connect(vault.getf('MONGODB_URI', { db: dbName })!)
}
export const openDatabase = async (mg: typeof mongoose, dbName = 'BattleLog') => {
if (!vault.get('MONGODB_URI')) throw 'No MongoDB URI, is your secrets file present and populated?'
return await mg.connect(vault.getf('MONGODB_URI', { db: dbName })!)
}

15
lib/fileExists.ts Normal file
View File

@@ -0,0 +1,15 @@
export const fileExists = async (path: string) => {
try {
await Deno.stat(path);
return true;
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
// file or directory does not exist
// console.log(error);
return false;
} else {
// unexpected error, maybe permissions, pass it along
throw error;
}
}
}

25
lib/jwt.ts Normal file
View File

@@ -0,0 +1,25 @@
import { create, verify, decode } from "https://deno.land/x/djwt@v2.8/mod.ts";
let key: CryptoKey;
try {
const storedKey = Deno.readTextFileSync('./key.txt');
key = await crypto.subtle.importKey('jwk', JSON.parse(storedKey), {name: 'HMAC', hash: 'SHA-512'}, true, ['sign', 'verify']);
} catch (error) {
key = await crypto.subtle.generateKey(
{ name: "HMAC", hash: {name: 'SHA-512'} },
true,
["sign", "verify"],
);
const keyToStore = await crypto.subtle.exportKey('jwk', key);
Deno.writeTextFileSync('./key.txt', JSON.stringify(keyToStore));
}
// console.log(key);
// Todo give this the user type
export const createUserSessionToken = async (user: any) => await create({ alg: 'HS512', typ: 'JWT' }, user, key);
export const verifyUserSessionToken = async (jwt: string) => await verify(jwt, key);
export const decodeUserSessionToken = async (jwt: string) => await decode(jwt);