diff --git a/backend/typescript/graphql/index.ts b/backend/typescript/graphql/index.ts index 10e0ad8d..076f9f69 100644 --- a/backend/typescript/graphql/index.ts +++ b/backend/typescript/graphql/index.ts @@ -13,11 +13,7 @@ import { } from "../middlewares/auth"; import authResolvers from "./resolvers/authResolvers"; import authType from "./types/authType"; -import entityResolvers from "./resolvers/entityResolvers"; -import entityType from "./types/entityType"; -import simpleEntityResolvers from "./resolvers/simpleEntityResolvers"; import adminResolvers from "./resolvers/adminResolvers"; -import simpleEntityType from "./types/simpleEntityType"; import userResolvers from "./resolvers/userResolvers"; import userType from "./types/userType"; import staffType from "./types/staffType"; @@ -46,9 +42,7 @@ const executableSchema = makeExecutableSchema({ query, mutation, authType, - entityType, residentType, - simpleEntityType, userType, taskType, staffType, @@ -57,9 +51,7 @@ const executableSchema = makeExecutableSchema({ resolvers: merge( scalarResolvers, authResolvers, - entityResolvers, residentResolvers, - simpleEntityResolvers, userResolvers, taskResolvers, staffResolver, @@ -73,21 +65,11 @@ const authorizedByAdmin = () => isAuthorizedByRole(new Set(["Admin"])); const graphQLMiddlewares = { Query: { - entity: authorizedByAllRoles(), - entities: authorizedByAllRoles(), - simpleEntity: authorizedByAllRoles(), - simpleEntities: authorizedByAllRoles(), userById: authorizedByAdmin(), userByEmail: authorizedByAdmin(), users: authorizedByAdmin(), }, Mutation: { - createEntity: authorizedByAllRoles(), - updateEntity: authorizedByAllRoles(), - deleteEntity: authorizedByAllRoles(), - createSimpleEntity: authorizedByAllRoles(), - updateSimpleEntity: authorizedByAllRoles(), - deleteSimpleEntity: authorizedByAllRoles(), createUser: authorizedByAdmin(), updateUser: authorizedByAdmin(), deleteUserById: authorizedByAdmin(), diff --git a/backend/typescript/graphql/resolvers/entityResolvers.ts b/backend/typescript/graphql/resolvers/entityResolvers.ts deleted file mode 100644 index 108a8b16..00000000 --- a/backend/typescript/graphql/resolvers/entityResolvers.ts +++ /dev/null @@ -1,132 +0,0 @@ -import fs from "fs"; -import { FileUpload } from "graphql-upload"; -/* eslint-disable-next-line import/no-extraneous-dependencies */ -import { ReadStream } from "fs-capacitor"; -import multer from "multer"; -import { - validateFileType, - getFileTypeValidationError, -} from "../../middlewares/validators/util"; -import EntityService from "../../services/implementations/entityService"; -import FileStorageService from "../../services/implementations/fileStorageService"; -import { - EntityRequestDTO, - EntityResponseDTO, -} from "../../services/interfaces/IEntityService"; -import { generateCSV } from "../../utilities/CSVUtils"; - -const defaultBucket = process.env.FIREBASE_STORAGE_DEFAULT_BUCKET || ""; -const fileStorageService = new FileStorageService(defaultBucket); -const entityService = new EntityService(fileStorageService); - -multer({ dest: "uploads/" }); - -const writeFile = (readStream: ReadStream, filePath: string): Promise => { - return new Promise((resolve, reject) => { - const out = fs.createWriteStream(filePath); - readStream.pipe(out); - out.on("finish", () => { - resolve(); - }); - out.on("error", (err) => reject(err)); - }); -}; - -const entityResolvers = { - Query: { - entity: async ( - _req: undefined, - { id }: { id: string }, - ): Promise => { - return entityService.getEntity(id); - }, - entities: async (): Promise => { - return entityService.getEntities(); - }, - entitiesCSV: async (): Promise => { - const entities = await entityService.getEntities(); - const csv = await generateCSV({ data: entities }); - return csv; - }, - file: async ( - _req: undefined, - { fileUUID }: { fileUUID: string }, - ): Promise => { - return fileStorageService.getFile(fileUUID); - }, - }, - Mutation: { - createEntity: async ( - _req: undefined, - { entity, file }: { entity: EntityRequestDTO; file: Promise }, - ): Promise => { - let filePath = ""; - let fileContentType = ""; - if (file) { - const { createReadStream, mimetype, filename } = await file; - const uploadDir = "uploads"; - filePath = `${uploadDir}/${filename}`; - fileContentType = mimetype; - if (!validateFileType(fileContentType)) { - throw new Error(getFileTypeValidationError(fileContentType)); - } - await writeFile(createReadStream(), filePath); - } - const newEntity = await entityService.createEntity({ - stringField: entity.stringField, - intField: entity.intField, - enumField: entity.enumField, - stringArrayField: entity.stringArrayField, - boolField: entity.boolField, - filePath, - fileContentType, - }); - if (filePath) { - fs.unlinkSync(filePath); - } - return newEntity; - }, - updateEntity: async ( - _req: undefined, - { - id, - entity, - file, - }: { id: string; entity: EntityRequestDTO; file: Promise }, - ): Promise => { - let filePath = ""; - let fileContentType = ""; - if (file) { - const { createReadStream, mimetype, filename } = await file; - const uploadDir = "uploads"; - filePath = `${uploadDir}/${filename}`; - fileContentType = mimetype; - if (!validateFileType(fileContentType)) { - throw new Error(getFileTypeValidationError(fileContentType)); - } - await writeFile(createReadStream(), filePath); - } - const updatedEntity = await entityService.updateEntity(id, { - stringField: entity.stringField, - intField: entity.intField, - enumField: entity.enumField, - stringArrayField: entity.stringArrayField, - boolField: entity.boolField, - filePath, - fileContentType, - }); - if (filePath) { - fs.unlinkSync(filePath); - } - return updatedEntity; - }, - deleteEntity: async ( - _req: undefined, - { id }: { id: string }, - ): Promise => { - return entityService.deleteEntity(id); - }, - }, -}; - -export default entityResolvers; diff --git a/backend/typescript/graphql/resolvers/simpleEntityResolvers.ts b/backend/typescript/graphql/resolvers/simpleEntityResolvers.ts deleted file mode 100644 index 64f90481..00000000 --- a/backend/typescript/graphql/resolvers/simpleEntityResolvers.ts +++ /dev/null @@ -1,63 +0,0 @@ -import SimpleEntityService from "../../services/implementations/simpleEntityService"; -import { - SimpleEntityRequestDTO, - SimpleEntityResponseDTO, -} from "../../services/interfaces/simpleEntityService"; -import { generateCSV } from "../../utilities/CSVUtils"; - -const simpleEntityService = new SimpleEntityService(); - -const entityResolvers = { - Query: { - simpleEntity: async ( - _req: undefined, - { id }: { id: string }, - ): Promise => { - return simpleEntityService.getEntity(id); - }, - simpleEntities: async (): Promise => { - return simpleEntityService.getEntities(); - }, - simpleEntitiesCSV: async (): Promise => { - const entities = await simpleEntityService.getEntities(); - const csv = await generateCSV({ - data: entities, - }); - return csv; - }, - }, - Mutation: { - createSimpleEntity: async ( - _req: undefined, - { entity }: { entity: SimpleEntityRequestDTO }, - ): Promise => { - return simpleEntityService.createEntity({ - stringField: entity.stringField, - intField: entity.intField, - enumField: entity.enumField, - stringArrayField: entity.stringArrayField, - boolField: entity.boolField, - }); - }, - updateSimpleEntity: async ( - _req: undefined, - { id, entity }: { id: string; entity: SimpleEntityRequestDTO }, - ): Promise => { - return simpleEntityService.updateEntity(id, { - stringField: entity.stringField, - intField: entity.intField, - enumField: entity.enumField, - stringArrayField: entity.stringArrayField, - boolField: entity.boolField, - }); - }, - deleteSimpleEntity: async ( - _req: undefined, - { id }: { id: string }, - ): Promise => { - return simpleEntityService.deleteEntity(id); - }, - }, -}; - -export default entityResolvers; diff --git a/backend/typescript/graphql/types/entityType.ts b/backend/typescript/graphql/types/entityType.ts deleted file mode 100644 index 50aea89d..00000000 --- a/backend/typescript/graphql/types/entityType.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { gql } from "apollo-server-express"; - -const entityType = gql` - enum Enum { - A - B - C - D - } - - scalar Upload - - type EntityResponseDTO { - id: ID! - stringField: String! - intField: Int! - enumField: Enum! - stringArrayField: [String]! - boolField: Boolean! - fileName: String - } - - input EntityRequestDTO { - stringField: String! - intField: Int! - enumField: Enum! - stringArrayField: [String]! - boolField: Boolean! - filePath: String - contentType: String - } - - extend type Query { - entity(id: ID!): EntityResponseDTO! - entities: [EntityResponseDTO!]! - entitiesCSV: String! - file(fileUUID: ID!): String! - } - - extend type Mutation { - createEntity(entity: EntityRequestDTO!, file: Upload): EntityResponseDTO! - updateEntity( - id: ID! - entity: EntityRequestDTO! - file: Upload - ): EntityResponseDTO! - deleteEntity(id: ID!): ID - } -`; - -export default entityType; diff --git a/backend/typescript/graphql/types/simpleEntityType.ts b/backend/typescript/graphql/types/simpleEntityType.ts deleted file mode 100644 index 11833cc5..00000000 --- a/backend/typescript/graphql/types/simpleEntityType.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { gql } from "apollo-server-express"; - -const simpleEntityType = gql` - enum SimpleEntityEnum { - A - B - C - D - } - - type SimpleEntityResponseDTO { - id: ID! - stringField: String! - intField: Int! - enumField: SimpleEntityEnum! - stringArrayField: [String]! - boolField: Boolean! - } - - input SimpleEntityRequestDTO { - stringField: String! - intField: Int! - enumField: Enum! - stringArrayField: [String]! - boolField: Boolean! - } - - extend type Query { - simpleEntity(id: ID!): SimpleEntityResponseDTO! - simpleEntities: [SimpleEntityResponseDTO!]! - simpleEntitiesCSV: String! - } - - extend type Mutation { - createSimpleEntity( - entity: SimpleEntityRequestDTO! - ): SimpleEntityResponseDTO! - updateSimpleEntity( - id: ID! - entity: SimpleEntityRequestDTO! - ): SimpleEntityResponseDTO! - deleteSimpleEntity(id: ID!): ID - } -`; - -export default simpleEntityType; diff --git a/backend/typescript/models/entity.model.ts b/backend/typescript/models/entity.model.ts deleted file mode 100644 index 5af3e1d7..00000000 --- a/backend/typescript/models/entity.model.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Column, Model, Table, DataType } from "sequelize-typescript"; - -import { Letters } from "../types"; - -@Table({ tableName: "entities" }) -export default class Entity extends Model { - @Column - string_field!: string; - - @Column - int_field!: number; - - @Column({ type: DataType.ENUM("A", "B", "C", "D") }) - enum_field!: Letters; - - @Column({ type: DataType.ARRAY(DataType.STRING) }) - string_array_field!: string[]; - - @Column - bool_field!: boolean; - - @Column - file_name!: string; -} diff --git a/backend/typescript/models/index.ts b/backend/typescript/models/index.ts deleted file mode 100644 index 0ca9ed25..00000000 --- a/backend/typescript/models/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -import * as path from "path"; -import { Sequelize } from "sequelize-typescript"; - -const DATABASE_URL = - process.env.NODE_ENV === "production" - ? /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */ - process.env.DATABASE_URL! - : `postgres://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.DB_HOST}:5432/${process.env.POSTGRES_DB_DEV}`; - -/* eslint-disable-next-line import/prefer-default-export */ -export const sequelize = new Sequelize(DATABASE_URL, { - models: [path.join(__dirname, "/*.model.ts")], -}); diff --git a/backend/typescript/models/simpleEntity.model.ts b/backend/typescript/models/simpleEntity.model.ts deleted file mode 100644 index a0169aa2..00000000 --- a/backend/typescript/models/simpleEntity.model.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Column, Model, Table, DataType } from "sequelize-typescript"; - -import { Letters } from "../types"; - -@Table({ tableName: "simple_entities" }) -export default class SimpleEntity extends Model { - @Column - string_field!: string; - - @Column - int_field!: number; - - @Column({ type: DataType.ENUM("A", "B", "C", "D") }) - enum_field!: Letters; - - @Column({ type: DataType.ARRAY(DataType.STRING) }) - string_array_field!: string[]; - - @Column - bool_field!: boolean; -} diff --git a/backend/typescript/prisma/schema.prisma b/backend/typescript/prisma/schema.prisma index 9296f5dc..ff6b2e3b 100644 --- a/backend/typescript/prisma/schema.prisma +++ b/backend/typescript/prisma/schema.prisma @@ -9,32 +9,6 @@ datasource db { // directUrl = env("DIRECT_URL") } -model post { - id Int @id @default(autoincrement()) - created_at DateTime @default(now()) - updated_at DateTime @updatedAt - title String @db.VarChar(255) - content String? - published Boolean @default(false) - author_id Int - author user @relation(fields: [author_id], references: [id]) -} - -model profile { - id Int @id @default(autoincrement()) - bio String? - user_id Int @unique - user user @relation(fields: [user_id], references: [id]) -} - -model user { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts post[] - profile profile? -} - model task { id Int @id @default(autoincrement()) category category @relation(fields: [categoryId], references: [id]) diff --git a/backend/typescript/server.ts b/backend/typescript/server.ts index 4d18206c..6ca3b4a2 100644 --- a/backend/typescript/server.ts +++ b/backend/typescript/server.ts @@ -4,7 +4,8 @@ import express from "express"; import * as firebaseAdmin from "firebase-admin"; import { ApolloServer } from "apollo-server-express"; -import { sequelize } from "./models"; +// TODO: verify can delete +//import { sequelize } from "./models"; import schema from "./graphql"; const CORS_ALLOW_LIST = [ @@ -41,7 +42,8 @@ server.applyMiddleware({ cors: { origin: CORS_ALLOW_LIST, credentials: true }, }); -sequelize.authenticate(); +// TODO: verify can delete +//sequelize.authenticate(); firebaseAdmin.initializeApp({ credential: firebaseAdmin.credential.cert({ diff --git a/backend/typescript/services/implementations/emailService.ts b/backend/typescript/services/implementations/emailService.ts index d7eeaf4a..41e4dbd3 100644 --- a/backend/typescript/services/implementations/emailService.ts +++ b/backend/typescript/services/implementations/emailService.ts @@ -41,4 +41,4 @@ class EmailService implements IEmailService { } } -export default EmailService; +export default EmailService; \ No newline at end of file diff --git a/backend/typescript/services/implementations/entityService.ts b/backend/typescript/services/implementations/entityService.ts deleted file mode 100644 index 24f848ce..00000000 --- a/backend/typescript/services/implementations/entityService.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { v4 as uuidv4 } from "uuid"; - -import PgEntity from "../../models/entity.model"; -import { - IEntityService, - EntityRequestDTO, - EntityResponseDTO, -} from "../interfaces/IEntityService"; -import IFileStorageService from "../interfaces/fileStorageService"; -import { getErrorMessage } from "../../utilities/errorUtils"; -import logger from "../../utilities/logger"; - -const Logger = logger(__filename); - -class EntityService implements IEntityService { - storageService: IFileStorageService; - - constructor(storageService: IFileStorageService) { - this.storageService = storageService; - } - - /* eslint-disable class-methods-use-this */ - async getEntity(id: string): Promise { - let entity: PgEntity | null; - try { - entity = await PgEntity.findByPk(id, { raw: true }); - if (!entity) { - throw new Error(`Entity id ${id} not found`); - } - } catch (error: unknown) { - Logger.error(`Failed to get entity. Reason = ${getErrorMessage(error)}`); - throw error; - } - - return { - id: String(entity.id), - stringField: entity.string_field, - intField: entity.int_field, - enumField: entity.enum_field, - stringArrayField: entity.string_array_field, - boolField: entity.bool_field, - fileName: entity.file_name, - }; - } - - async getEntities(): Promise { - try { - const entities: Array = await PgEntity.findAll({ raw: true }); - return entities.map((entity) => ({ - id: String(entity.id), - stringField: entity.string_field, - intField: entity.int_field, - enumField: entity.enum_field, - stringArrayField: entity.string_array_field, - boolField: entity.bool_field, - fileName: entity.file_name, - })); - } catch (error: unknown) { - Logger.error( - `Failed to get entities. Reason = ${getErrorMessage(error)}`, - ); - throw error; - } - } - - async createEntity(entity: EntityRequestDTO): Promise { - let newEntity: PgEntity | null; - const fileName = entity.filePath ? uuidv4() : ""; - try { - if (entity.filePath) { - await this.storageService.createFile( - fileName, - entity.filePath, - entity.fileContentType, - ); - } - newEntity = await PgEntity.create({ - string_field: entity.stringField, - int_field: entity.intField, - enum_field: entity.enumField, - string_array_field: entity.stringArrayField, - bool_field: entity.boolField, - file_name: fileName, - }); - } catch (error: unknown) { - Logger.error( - `Failed to create entity. Reason = ${getErrorMessage(error)}`, - ); - throw error; - } - return { - id: String(newEntity.id), - stringField: newEntity.string_field, - intField: newEntity.int_field, - enumField: newEntity.enum_field, - stringArrayField: newEntity.string_array_field, - boolField: newEntity.bool_field, - fileName, - }; - } - - async updateEntity( - id: string, - entity: EntityRequestDTO, - ): Promise { - let resultingEntity: PgEntity | null; - let updateResult: [number, PgEntity[]] | null; - let fileName = ""; - try { - const currentEntity = await PgEntity.findByPk(id, { - raw: true, - attributes: ["file_name"], - }); - const currentFileName = currentEntity?.file_name; - if (entity.filePath) { - fileName = currentFileName || uuidv4(); - if (currentFileName) { - await this.storageService.updateFile( - fileName, - entity.filePath, - entity.fileContentType, - ); - } else { - await this.storageService.createFile( - fileName, - entity.filePath, - entity.fileContentType, - ); - } - } else if (currentFileName) { - await this.storageService.deleteFile(currentFileName); - } - updateResult = await PgEntity.update( - { - string_field: entity.stringField, - int_field: entity.intField, - enum_field: entity.enumField, - string_array_field: entity.stringArrayField, - bool_field: entity.boolField, - file_name: fileName, - }, - { where: { id }, returning: true }, - ); - - if (!updateResult[0]) { - throw new Error(`Entity id ${id} not found`); - } - [, [resultingEntity]] = updateResult; - } catch (error: unknown) { - Logger.error( - `Failed to update entity. Reason = ${getErrorMessage(error)}`, - ); - throw error; - } - return { - id: String(resultingEntity.id), - stringField: resultingEntity.string_field, - intField: resultingEntity.int_field, - enumField: resultingEntity.enum_field, - stringArrayField: resultingEntity.string_array_field, - boolField: resultingEntity.bool_field, - fileName, - }; - } - - async deleteEntity(id: string): Promise { - try { - const entityToDelete = await PgEntity.findByPk(id, { raw: true }); - const deleteResult: number | null = await PgEntity.destroy({ - where: { id }, - }); - - if (!entityToDelete || !deleteResult) { - throw new Error(`Entity id ${id} not found`); - } - if (entityToDelete.file_name) { - await this.storageService.deleteFile(entityToDelete.file_name); - } - return id; - } catch (error: unknown) { - Logger.error( - `Failed to delete entity. Reason = ${getErrorMessage(error)}`, - ); - throw error; - } - } -} - -export default EntityService; diff --git a/backend/typescript/services/implementations/simpleEntityService.ts b/backend/typescript/services/implementations/simpleEntityService.ts deleted file mode 100644 index 1b5ceb92..00000000 --- a/backend/typescript/services/implementations/simpleEntityService.ts +++ /dev/null @@ -1,141 +0,0 @@ -import PgSimpleEntity from "../../models/simpleEntity.model"; -import { - ISimpleEntityService, - SimpleEntityRequestDTO, - SimpleEntityResponseDTO, -} from "../interfaces/simpleEntityService"; -import { getErrorMessage } from "../../utilities/errorUtils"; -import logger from "../../utilities/logger"; - -const Logger = logger(__filename); - -class SimpleEntityService implements ISimpleEntityService { - /* eslint-disable class-methods-use-this */ - async getEntity(id: string): Promise { - let entity: PgSimpleEntity | null; - try { - entity = await PgSimpleEntity.findByPk(id, { raw: true }); - if (!entity) { - throw new Error(`Entity id ${id} not found`); - } - } catch (error: unknown) { - Logger.error(`Failed to get entity. Reason = ${getErrorMessage(error)}`); - throw error; - } - - return { - id: String(entity.id), - stringField: entity.string_field, - intField: entity.int_field, - enumField: entity.enum_field, - stringArrayField: entity.string_array_field, - boolField: entity.bool_field, - }; - } - - async getEntities(): Promise { - try { - const entities: Array = await PgSimpleEntity.findAll({ - raw: true, - }); - return entities.map((entity) => ({ - id: String(entity.id), - stringField: entity.string_field, - intField: entity.int_field, - enumField: entity.enum_field, - stringArrayField: entity.string_array_field, - boolField: entity.bool_field, - })); - } catch (error: unknown) { - Logger.error( - `Failed to get entities. Reason = ${getErrorMessage(error)}`, - ); - throw error; - } - } - - async createEntity( - entity: SimpleEntityRequestDTO, - ): Promise { - let newEntity: PgSimpleEntity | null; - try { - newEntity = await PgSimpleEntity.create({ - string_field: entity.stringField, - int_field: entity.intField, - enum_field: entity.enumField, - string_array_field: entity.stringArrayField, - bool_field: entity.boolField, - }); - } catch (error: unknown) { - Logger.error( - `Failed to create entity. Reason = ${getErrorMessage(error)}`, - ); - throw error; - } - return { - id: String(newEntity.id), - stringField: newEntity.string_field, - intField: newEntity.int_field, - enumField: newEntity.enum_field, - stringArrayField: newEntity.string_array_field, - boolField: newEntity.bool_field, - }; - } - - async updateEntity( - id: string, - entity: SimpleEntityRequestDTO, - ): Promise { - let resultingEntity: PgSimpleEntity | null; - let updateResult: [number, PgSimpleEntity[]] | null; - try { - updateResult = await PgSimpleEntity.update( - { - string_field: entity.stringField, - int_field: entity.intField, - enum_field: entity.enumField, - string_array_field: entity.stringArrayField, - bool_field: entity.boolField, - }, - { where: { id }, returning: true }, - ); - - if (!updateResult[0]) { - throw new Error(`Entity id ${id} not found`); - } - [, [resultingEntity]] = updateResult; - } catch (error: unknown) { - Logger.error( - `Failed to update entity. Reason = ${getErrorMessage(error)}`, - ); - throw error; - } - return { - id: String(resultingEntity.id), - stringField: resultingEntity.string_field, - intField: resultingEntity.int_field, - enumField: resultingEntity.enum_field, - stringArrayField: resultingEntity.string_array_field, - boolField: resultingEntity.bool_field, - }; - } - - async deleteEntity(id: string): Promise { - try { - const deleteResult: number | null = await PgSimpleEntity.destroy({ - where: { id }, - }); - if (!deleteResult) { - throw new Error(`Entity id ${id} not found`); - } - return id; - } catch (error: unknown) { - Logger.error( - `Failed to delete entity. Reason = ${getErrorMessage(error)}`, - ); - throw error; - } - } -} - -export default SimpleEntityService; diff --git a/backend/typescript/services/implementations/userService.ts b/backend/typescript/services/implementations/userService.ts index 79c8c114..a78960a6 100644 --- a/backend/typescript/services/implementations/userService.ts +++ b/backend/typescript/services/implementations/userService.ts @@ -15,12 +15,12 @@ class UserService implements IUserService { let firebaseUser: firebaseAdmin.auth.UserRecord; try { - user = await User.findByPk(Number(userId)); + user = await User.findByPk(Number(userId)); // sequelize if (!user) { throw new Error(`userId ${userId} not found.`); } - firebaseUser = await firebaseAdmin.auth().getUser(user.auth_id); + firebaseUser = await firebaseAdmin.auth().getUser(user.auth_id); } catch (error: unknown) { Logger.error(`Failed to get user. Reason = ${getErrorMessage(error)}`); throw error; @@ -64,7 +64,7 @@ class UserService implements IUserService { async getUserRoleByAuthId(authId: string): Promise { try { - const user: User | null = await User.findOne({ + const user: User | null = await User.findOne({ // sequelize where: { auth_id: authId }, }); if (!user) { @@ -81,7 +81,7 @@ class UserService implements IUserService { async getUserIdByAuthId(authId: string): Promise { try { - const user: User | null = await User.findOne({ + const user: User | null = await User.findOne({ // sequelize where: { auth_id: authId }, }); if (!user) { @@ -96,7 +96,7 @@ class UserService implements IUserService { async getAuthIdById(userId: string): Promise { try { - const user: User | null = await User.findByPk(Number(userId)); + const user: User | null = await User.findByPk(Number(userId)); // sequelize if (!user) { throw new Error(`userId ${userId} not found.`); } @@ -110,7 +110,7 @@ class UserService implements IUserService { async getUsers(): Promise> { let userDtos: Array = []; try { - const users: Array = await User.findAll(); + const users: Array = await User.findAll(); // sequelize userDtos = await Promise.all( users.map(async (user) => { @@ -163,7 +163,7 @@ class UserService implements IUserService { } try { - newUser = await User.create({ + newUser = await User.create({ // sequelize first_name: user.firstName, last_name: user.lastName, auth_id: firebaseUser.uid, @@ -202,7 +202,7 @@ class UserService implements IUserService { let updatedFirebaseUser: firebaseAdmin.auth.UserRecord; try { - const updateResult = await User.update( + const updateResult = await User.update( // sequelize { first_name: user.firstName, last_name: user.lastName, @@ -231,7 +231,7 @@ class UserService implements IUserService { } catch (error) { // rollback Postgres user updates try { - await User.update( + await User.update( // sequelize { first_name: oldUser.first_name, last_name: oldUser.last_name, @@ -270,13 +270,13 @@ class UserService implements IUserService { async deleteUserById(userId: string): Promise { try { // Sequelize doesn't provide a way to atomically find, delete, and return deleted row - const deletedUser: User | null = await User.findByPk(Number(userId)); + const deletedUser: User | null = await User.findByPk(Number(userId)); // sequelize if (!deletedUser) { throw new Error(`userid ${userId} not found.`); } - const numDestroyed: number = await User.destroy({ + const numDestroyed: number = await User.destroy({ // sequelize where: { id: userId }, }); @@ -318,7 +318,7 @@ class UserService implements IUserService { const firebaseUser: firebaseAdmin.auth.UserRecord = await firebaseAdmin .auth() .getUserByEmail(email); - const deletedUser: User | null = await User.findOne({ + const deletedUser: User | null = await User.findOne({ // sequelize where: { auth_id: firebaseUser.uid }, }); @@ -326,7 +326,7 @@ class UserService implements IUserService { throw new Error(`userid ${firebaseUser.uid} not found.`); } - const numDestroyed: number = await User.destroy({ + const numDestroyed: number = await User.destroy({ // sequelize where: { auth_id: firebaseUser.uid }, }); @@ -341,7 +341,7 @@ class UserService implements IUserService { } catch (error) { // rollback user deletion in Postgres try { - await User.create({ + await User.create({ // sequelize first_name: deletedUser.first_name, last_name: deletedUser.last_name, auth_id: deletedUser.auth_id, diff --git a/backend/typescript/services/interfaces/IEntityService.ts b/backend/typescript/services/interfaces/IEntityService.ts deleted file mode 100644 index 80573137..00000000 --- a/backend/typescript/services/interfaces/IEntityService.ts +++ /dev/null @@ -1,65 +0,0 @@ -export interface EntityRequestDTO { - stringField: string; - intField: number; - enumField: string; - stringArrayField: string[]; - boolField: boolean; - filePath?: string; - fileContentType?: string; -} - -export interface EntityResponseDTO { - id: string; - stringField: string; - intField: number; - enumField: string; - stringArrayField: string[]; - boolField: boolean; - fileName: string; -} - -export interface IEntityService { - /** - * retrieve the Entity with the given id - * @param id entity id - * @returns requested Entity - * @throws Error if retrieval fails - */ - getEntity(id: string): Promise; - - /** - * retrieve all Entities - * @param - * @returns returns array of Entities - * @throws Error if retrieval fails - */ - getEntities(): Promise; - - /** - * create an Entity with the fields given in the DTO, return created Entity - * @param entity new Entity - * @returns the created Entity - * @throws Error if creation fails - */ - createEntity(entity: EntityRequestDTO): Promise; - - /** - * update the Entity with the given id with fields in the DTO, return updated Entity - * @param id entity id - * @param entity Updated Entity - * @returns the updated Entity - * @throws Error if update fails - */ - updateEntity( - id: string, - entity: EntityRequestDTO, - ): Promise; - - /** - * delete the entity with the given id - * @param id entity id - * @returns id of the entity deleted - * @throws Error if deletion fails - */ - deleteEntity(id: string): Promise; -} diff --git a/backend/typescript/services/interfaces/emailService.ts b/backend/typescript/services/interfaces/emailService.ts index c56dca4d..ccd0376b 100644 --- a/backend/typescript/services/interfaces/emailService.ts +++ b/backend/typescript/services/interfaces/emailService.ts @@ -1,12 +1,12 @@ interface IEmailService { - /** - * Send email - * @param to recipient's email - * @param subject email subject - * @param htmlBody email body as html - * @throws Error if email was not sent successfully - */ - sendEmail(to: string, subject: string, htmlBody: string): Promise; -} - -export default IEmailService; + /** + * Send email + * @param to recipient's email + * @param subject email subject + * @param htmlBody email body as html + * @throws Error if email was not sent successfully + */ + sendEmail(to: string, subject: string, htmlBody: string): Promise; + } + + export default IEmailService; \ No newline at end of file diff --git a/backend/typescript/services/interfaces/simpleEntityService.ts b/backend/typescript/services/interfaces/simpleEntityService.ts deleted file mode 100644 index 41b33b3f..00000000 --- a/backend/typescript/services/interfaces/simpleEntityService.ts +++ /dev/null @@ -1,64 +0,0 @@ -export interface SimpleEntityRequestDTO { - stringField: string; - intField: number; - enumField: string; - stringArrayField: string[]; - boolField: boolean; -} - -export interface SimpleEntityResponseDTO { - id: string; - stringField: string; - intField: number; - enumField: string; - stringArrayField: string[]; - boolField: boolean; -} - -export interface ISimpleEntityService { - /** - * retrieve the SimpleEntity with the given id - * @param id SimpleEntity id - * @returns requested SimpleEntity - * @throws Error if retrieval fails - */ - getEntity(id: string): Promise; - - /** - * retrieve all SimpleEntities - * @param - * @returns returns array of SimpleEntities - * @throws Error if retrieval fails - */ - getEntities(): Promise; - - /** - * create a SimpleEntity with the fields given in the DTO, return created SimpleEntity - * @param entity new SimpleEntity - * @returns the created SimpleEntity - * @throws Error if creation fails - */ - createEntity( - entity: SimpleEntityRequestDTO, - ): Promise; - - /** - * update the SimpleEntity with the given id with fields in the DTO, return updated SimpleEntity - * @param id SimpleEntity id - * @param entity Updated SimpleEntity - * @returns the updated SimpleEntity - * @throws Error if update fails - */ - updateEntity( - id: string, - entity: SimpleEntityRequestDTO, - ): Promise; - - /** - * delete the SimpleEntity with the given id - * @param id SimpleEntity id - * @returns id of the SimpleEntity deleted - * @throws Error if deletion fails - */ - deleteEntity(id: string): Promise; -} diff --git a/backend/typescript/umzug.ts b/backend/typescript/umzug.ts deleted file mode 100644 index 077322de..00000000 --- a/backend/typescript/umzug.ts +++ /dev/null @@ -1,27 +0,0 @@ -import * as path from "path"; - -import { Umzug, SequelizeStorage } from "umzug"; -import { Sequelize } from "sequelize-typescript"; - -const DATABASE_URL = - process.env.NODE_ENV === "production" - ? /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */ - process.env.DATABASE_URL! - : `postgres://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.DB_HOST}:5432/${process.env.POSTGRES_DB_DEV}`; - -const sequelize = new Sequelize(DATABASE_URL, { - models: [path.join(__dirname, "/*.model.ts")], -}); - -export const migrator = new Umzug({ - migrations: { - glob: ["migrations/*.ts", { cwd: __dirname }], - }, - context: sequelize, - storage: new SequelizeStorage({ - sequelize, - }), - logger: console, -}); - -export type Migration = typeof migrator._types.migration;