Updated Repository

Repositories and controllers are merged, since the functions would just be really redundant thanks to TypeORM
This commit is contained in:
Alexis
2021-08-02 16:44:40 +02:00
parent f12190c95a
commit 884edba504
8 changed files with 49 additions and 104 deletions

View File

@@ -44,8 +44,7 @@ export class AuracleApi {
}
/**
* Links the API with a Sequelize Database Object
* @param db_driver A Sequelize instance
* Links the API with a TypeORM connection
*/
private db_connect = async (db_driver: Promise<Connection>) => {
try {

View File

@@ -1,9 +1,9 @@
import { AuracleApiRepository } from "./AuracleApiRepository";
import { getRepository, Repository } from "typeorm";
export class AuracleApiController {
public repository: AuracleApiRepository
public repository: Repository<any>
constructor(repository: AuracleApiRepository) {
this.repository = repository
constructor() {
// Todo
}
}

View File

@@ -1,9 +0,0 @@
import { Model } from "sequelize/types";
export class AuracleApiRepository {
public model: Model<any, any>
constructor(model: Model<any, any>) {
this.model = model
}
}

View File

@@ -1,21 +1,19 @@
import express from 'express';
import { getRepository, Repository } from 'typeorm';
import { AuracleApiController } from "../common/classes/AuracleApiController";
import { AuracleApiResponse } from '../common/classes/AuracleApiResponse';
import { Spell, SpellCreationAttributes } from '../database/models/spells/Spell';
import { SpellRepository } from "../repositories/SpellRepository";
import { Spell } from '../database/models/spells/Spell';
export class SpellController extends AuracleApiController {
public repository: SpellRepository
constructor() {
super(new SpellRepository)
super()
}
public async getAll(req: express.Request, res: express.Response) {
let spells: Spell[]
try {
spells = await this.repository.fetchAll()
spells = await getRepository(Spell).find()
res = new AuracleApiResponse(200, spells).send(res)
} catch (err) {
res = new AuracleApiResponse(400).send(res)
@@ -27,7 +25,7 @@ export class SpellController extends AuracleApiController {
let spell: Spell
try {
spell = await this.repository.fetchOne(uuid)
spell = await getRepository(Spell).findOne(uuid)
res = new AuracleApiResponse(200, spell).send(res)
} catch (err) {
res = new AuracleApiResponse(400).send(res)
@@ -42,10 +40,10 @@ export class SpellController extends AuracleApiController {
charge: req.body.charge,
cost: req.body.cost,
isRitual: req.body.isRitual
} as SpellCreationAttributes
}
try {
const newSpell = await this.repository.createOne(spell)
const newSpell = getRepository(Spell).insert(spell)
res = new AuracleApiResponse(201, newSpell).send(res)
} catch (err) {
console.log(err)

View File

@@ -1,38 +1,8 @@
import * as fs from 'fs'
import { createConnection } from 'typeorm';
import { dbConfig } from './config'
export const AuracleDatabaseDriver = createConnection(dbConfig);
/**
* Fetches all Typescript files from a given directory
*
* @param dir The folder to scan where the models are located
* @param acc (Optional) The array to start
* @returns All .ts files within the dir
*/
export const fetchAllTypescriptFiles = (dir: string, acc: string[] = []): string[] => {
fs.readdirSync(dir)
.forEach(file => {
const fileIsTypescript = (file.split('.').pop() === 'ts')
const fileIsFolder = (file.indexOf('.') === -1)
if (fileIsFolder) {
fetchAllTypescriptFiles(`${dir}/${file}`, acc)
}
if (fileIsTypescript) {
acc.push(`${dir}/${file}`)
}
})
return acc
}
const modelDir = __dirname + '/models'
const models = fetchAllTypescriptFiles(modelDir)
/**
* If the environement is production, sync the DB
*/

View File

@@ -1,5 +1,7 @@
import { MysqlConnectionOptions } from "typeorm/driver/mysql/MysqlConnectionOptions"
import * as fs from 'fs'
import { Spell } from "../models/spells/Spell"
import { School } from "../models/spells/School"
import { Variable } from "../models/spells/Variable"
@@ -11,6 +13,35 @@ import { Role } from "../models/users/Role"
const tablePrefix = 'au_'
/**
* Fetches all Typescript files from a given directory
*
* @param dir The folder to scan where the models are located
* @param acc (Optional) The array to start
* @returns All .ts files within the dir
*/
export const fetchAllTypescriptFiles = (dir: string, acc: string[] = []): string[] => {
fs.readdirSync(dir)
.forEach(file => {
const fileIsTypescript = (file.split('.').pop() === 'ts')
const fileIsFolder = (file.indexOf('.') === -1)
if (fileIsFolder) {
fetchAllTypescriptFiles(`${dir}/${file}`, acc)
}
if (fileIsTypescript) {
acc.push(`${dir}/${file}`)
}
})
return acc
}
const modelDir = './src/database/models/'
const models = fetchAllTypescriptFiles(modelDir)
/**
* Registers the options to create the sequelize instance
*/
@@ -26,16 +57,5 @@ export const dbConfig: MysqlConnectionOptions = {
logging: false,
entityPrefix: tablePrefix,
entities: [
User,
Permission,
Role,
Spell,
School,
MetaSchool,
Variable,
Ingredient,
]
entities: models
}

View File

@@ -24,31 +24,18 @@ const apiPort = process.env.API_PORT
const app = new AuracleApi({
port: apiPort,
database: AuracleDatabaseDriver,
middlewares: [],
routers: [],
routers: [
new SpellRouter
],
modules: [
express.json({ limit: '10kb' }),
morgan('dev'),
helmet()
],
database: AuracleDatabaseDriver
})
// Listens on apiPort...
app.listen()
// const routes = require('./routes');
// // Server
// app.listen(port, () => console.log(`App listening on port ${port}`));
// // Entry route
// app.use('/api/v1/', routes.auth);
// // Routing
// app.use('/api/v1/spells', routes.spells);
// app.use('/api/v1/schools', routes.schools);
// app.use('/api/v1/meta_schools', routes.meta_schools);
// app.use('/api/v1/variables', routes.variables);
// app.use('/api/v1/ingredients', routes.ingredients);
// app.use('/api/v1/users', routes.users);

View File

@@ -1,20 +0,0 @@
import { AuracleApiRepository } from "../common/classes/AuracleApiRepository"
import { Spell, SpellCreationAttributes } from "../database/models/spells/Spell"
export class SpellRepository extends AuracleApiRepository {
constructor() {
super(new Spell)
}
public async fetchAll(): Promise<Spell[]> {
return Spell.findAll()
}
public async fetchOne(uuid: string): Promise<Spell> {
return Spell.findByPk(uuid)
}
public async createOne(spell: SpellCreationAttributes): Promise<Spell> {
return Spell.create(spell)
}
}