Skip to content

Commit

Permalink
update config
Browse files Browse the repository at this point in the history
  • Loading branch information
mariovyord committed Jan 8, 2024
1 parent 58c760e commit 04dcfd2
Show file tree
Hide file tree
Showing 14 changed files with 58 additions and 46 deletions.
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@ ALLOW_ORIGIN="*"
ALLOW_METHODS="GET,PUT,POST,PATCH,DELETE,HEAD,OPTIONS"
ALLOW_HEADERS="Content-Type,Cache-Control,Expires"
JWT_SECRET=SUPERSECRET
DB_HOST=host.docker.internal
DB_PORT=6543
DB_USERNAME=postgres
DB_PASSWORD=123123
6 changes: 4 additions & 2 deletions .env.local.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@ ALLOW_ORIGIN="*"
ALLOW_METHODS="GET,PUT,POST,PATCH,DELETE,HEAD,OPTIONS"
ALLOW_HEADERS="Content-Type,Cache-Control,Expires"
JWT_SECRET=SUPERSECRET
CONNECTION_STRING="mongodb://localhost:27017/express-template" # When started locally
# CONNECTION_STRING="mongodb://express-ts-api-mongo-1:27017/express-template" # When started in docker dev mode
DB_HOST=host.docker.internal
DB_PORT=6543
DB_USERNAME=postgres
DB_PASSWORD=123123
2 changes: 1 addition & 1 deletion docker-compose-debug.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Overlay configuration to enable debuggers
version: "3.9"
version: "3"
services:
app:
command:
Expand Down
1 change: 0 additions & 1 deletion docker-compose-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ services:

postgres_db:
image: postgres:latest
container_name: postgres_db
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=123123
Expand Down
1 change: 0 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ services:

postgres_db:
image: postgres:latest
container_name: postgres_db
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=123123
Expand Down
13 changes: 8 additions & 5 deletions src/config/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@ import "reflect-metadata";
import { Article } from "../features/article/article-entity";
import { Comment } from "../features/comment/comment-entity";
import { User } from "../features/user/user-entity";
import getConfig from "./get-config";

const config = getConfig();

export const AppDataSource = new DataSource({
type: "postgres",
host: "localhost",
port: 6543,
password: "123123",
username: "postgres",
host: config.DB_HOST,
port: parseInt(config.DB_PORT),
username: config.DB_USERNAME,
password: config.DB_PASSWORD,
database: "express_app",
synchronize: true,
synchronize: config.NODE_ENV === "production" ? false : true,
logging: true,
entities: [Article, Comment, User],
});
14 changes: 13 additions & 1 deletion src/config/get-config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import dotenv from "dotenv";

/**
* Load enviroment variables
*/
dotenv.config();
dotenv.config({ path: `.env.local`, override: true });

export default function getConfig() {
console.log(process.env);
return {
NODE_ENV: process.env.NODE_ENV,
PORT: process.env.PORT,
ALLOW_ORIGIN: process.env.ALLOW_ORIGIN,
ALLOW_METHODS: process.env.ALLOW_METHODS,
ALLOW_HEADERS: process.env.ALLOW_HEADERS,
CONNECTION_STRING: process.env.CONNECTION_STRING,
JWT_SECRET: process.env.JWT_SECRET,
DB_HOST: process.env.DB_HOST,
DB_PORT: process.env.DB_PORT,
DB_PASSWORD: process.env.DB_PASSWORD,
DB_USERNAME: process.env.DB_USERNAME,
};
}
2 changes: 1 addition & 1 deletion src/features/article/article-repository.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AppDataSource } from "../../config/db";
import { Article } from "./article-entity";

export const articleRepository = () => AppDataSource.getRepository(Article);
export const getArticleRepository = () => AppDataSource.getRepository(Article);
16 changes: 8 additions & 8 deletions src/features/article/article-service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { NotFoundError, UnauthorizedError } from "../../utils/app-error";
import { IFullQuery, buildQuery } from "../../utils/build-query";
import { Article } from "./article-entity";
import { articleRepository } from "./article-repository";
import { getArticleRepository } from "./article-repository";
import { ArticleDto, ICreateArticleData, IPutArticleData } from "./article-types";

export async function getAll(query: IFullQuery): Promise<ArticleDto[]> {
const articles = await buildQuery(articleRepository(), query);
const articles = await buildQuery(getArticleRepository(), query);

if (!articles) {
return [];
Expand All @@ -15,7 +15,7 @@ export async function getAll(query: IFullQuery): Promise<ArticleDto[]> {
}

export async function getOne(id: string, query: any): Promise<ArticleDto> {
let queryBuilder = articleRepository().createQueryBuilder("entity");
let queryBuilder = getArticleRepository().createQueryBuilder("entity");

queryBuilder = queryBuilder.where("entity.id = :id", { id });

Expand All @@ -40,15 +40,15 @@ export async function create(data: ICreateArticleData & { owner: string }): Prom
article.created_at = new Date();
article.updated_at = new Date();

await articleRepository().save(article);
await getArticleRepository().save(article);

return new ArticleDto(article);
}

const ALLOWED_UPDATE_FIELDS = ["title", "content"];

export async function update(id: string, userId: string, data: IPutArticleData): Promise<ArticleDto> {
const article = await articleRepository().findOneBy({ id });
const article = await getArticleRepository().findOneBy({ id });

if (article === null) throw new NotFoundError();
if (article.owner.toString() !== userId) throw new UnauthorizedError();
Expand All @@ -61,16 +61,16 @@ export async function update(id: string, userId: string, data: IPutArticleData):

article.updated_at = new Date();

await articleRepository().save(article);
await getArticleRepository().save(article);

return new ArticleDto(article);
}

export async function remove(id: string, userId: string): Promise<void> {
const article = await articleRepository().findOneBy({ id });
const article = await getArticleRepository().findOneBy({ id });

if (!article) throw new NotFoundError();
if (article.owner !== userId) throw new UnauthorizedError();

await articleRepository().remove(article);
await getArticleRepository().remove(article);
}
2 changes: 1 addition & 1 deletion src/features/comment/comment-repository.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AppDataSource } from "../../config/db";
import { Comment } from "./comment-entity";

export const commentRepository = () => AppDataSource.getRepository(Comment);
export const getCommentRepository = () => AppDataSource.getRepository(Comment);
16 changes: 8 additions & 8 deletions src/features/comment/comment-service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { NotFoundError, UnauthorizedError } from "../../utils/app-error";
import { IFullQuery, buildQuery } from "../../utils/build-query";
import { Comment } from "./comment-entity";
import { commentRepository } from "./comment-repository";
import { getCommentRepository } from "./comment-repository";
import { CommentDto, ICreateCommentData, IPutCommentData } from "./comment-types";

export async function getAllComments(query: IFullQuery): Promise<CommentDto[] | number> {
const comments = await buildQuery(commentRepository(), query);
const comments = await buildQuery(getCommentRepository(), query);

if (!comments) {
return [];
Expand All @@ -15,7 +15,7 @@ export async function getAllComments(query: IFullQuery): Promise<CommentDto[] |
}

export async function getOneComment(id: string, query: any): Promise<CommentDto | null> {
let queryBuilder = commentRepository().createQueryBuilder("entity");
let queryBuilder = getCommentRepository().createQueryBuilder("entity");

queryBuilder = queryBuilder.where("entity.id = :id", { id });

Expand All @@ -41,15 +41,15 @@ export async function createComment(data: ICreateCommentData & { owner: string }
comment.updated_at = new Date();
comment.owner = data.owner;

await commentRepository().save(comment);
await getCommentRepository().save(comment);

return new CommentDto(comment);
}

const ALLOWED_UPDATE_FIELDS = ["content"];

export async function updateComment(id: string, userId: string, data: IPutCommentData): Promise<CommentDto> {
const comment = await commentRepository().findOneBy({ id });
const comment = await getCommentRepository().findOneBy({ id });

if (comment === null) throw new NotFoundError();
if (comment.owner !== userId) throw new UnauthorizedError();
Expand All @@ -62,16 +62,16 @@ export async function updateComment(id: string, userId: string, data: IPutCommen

comment.updated_at = new Date();

await commentRepository().save(comment);
await getCommentRepository().save(comment);

return new CommentDto(comment);
}

export async function deleteComment(id: string, userId: string): Promise<void> {
const comment = await commentRepository().findOneBy({ id });
const comment = await getCommentRepository().findOneBy({ id });

if (!comment) throw new NotFoundError();
if (comment.owner !== userId) throw new UnauthorizedError();

await commentRepository().remove(comment);
await getCommentRepository().remove(comment);
}
2 changes: 1 addition & 1 deletion src/features/user/user-repository.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AppDataSource } from "../../config/db";
import { User } from "./user-entity";

export const userRepository = () => AppDataSource.getRepository(User);
export const getUserRepository = () => AppDataSource.getRepository(User);
18 changes: 9 additions & 9 deletions src/features/user/user-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import getConfig from "../../config/get-config";
import { IUserLocal, ISignUpUserData, UserDto, IUpdateUserData } from "./user-types";
import { BadRequestError, InternalServerError, NotFoundError, UnauthorizedError } from "../../utils/app-error";
import { User } from "./user-entity";
import { userRepository } from "./user-repository";
import { getUserRepository } from "./user-repository";

export async function signUp(userData: ISignUpUserData): Promise<[string, UserDto]> {
if (!userData.username) {
throw new BadRequestError();
}

const existing = await userRepository().findOneBy({
const existing = await getUserRepository().findOneBy({
username: userData.username.toLowerCase(),
});

Expand All @@ -26,7 +26,7 @@ export async function signUp(userData: ISignUpUserData): Promise<[string, UserDt
user.created_at = new Date();
user.updated_at = new Date();

await userRepository().save(user);
await getUserRepository().save(user);

const token = await createToken(user.id);

Expand All @@ -38,7 +38,7 @@ export async function signIn(username: string, password: string): Promise<[strin
throw new BadRequestError();
}

const user = await userRepository().findOneBy({
const user = await getUserRepository().findOneBy({
username: username.toLowerCase(),
});

Expand Down Expand Up @@ -70,7 +70,7 @@ async function createToken(id: string) {
}

export async function getUser(userData: IUserLocal): Promise<UserDto> {
const user = await userRepository().findOneBy({ id: userData.id });
const user = await getUserRepository().findOneBy({ id: userData.id });
if (!user) {
throw new NotFoundError();
}
Expand All @@ -81,7 +81,7 @@ export async function getUser(userData: IUserLocal): Promise<UserDto> {
const ALLOWED_UPDATE_FIELDS = ["firstName", "lastName"];

export async function updateUser(userId: string, userData: Partial<IUpdateUserData>): Promise<UserDto> {
const user = await userRepository().findOneBy({ id: userId });
const user = await getUserRepository().findOneBy({ id: userId });

if (!user || user.id !== userId) {
throw new UnauthorizedError();
Expand All @@ -95,13 +95,13 @@ export async function updateUser(userId: string, userData: Partial<IUpdateUserDa

user.updated_at = new Date();

await userRepository().save(user);
await getUserRepository().save(user);

return new UserDto(user);
}

export async function updatePassword(userId: string, oldPassword: string, newPassword: string) {
const user = await userRepository().findOneBy({ id: userId });
const user = await getUserRepository().findOneBy({ id: userId });

if (!user) {
throw new NotFoundError();
Expand All @@ -117,7 +117,7 @@ export async function updatePassword(userId: string, oldPassword: string, newPas

user.updated_at = new Date();

await userRepository().save(user);
await getUserRepository().save(user);

return user;
}
7 changes: 0 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
import app from "./app";
import { AppDataSource } from "./config/db";
import getConfig from "./config/get-config";
import dotenv from "dotenv";
import { AppError } from "./utils/app-error";

/**
* Load enviroment variables
*/
dotenv.config();
dotenv.config({ path: `.env.local`, override: true });

const config = getConfig();
const port: number = config.PORT ? parseInt(config.PORT) : 5000;

Expand Down

0 comments on commit 04dcfd2

Please sign in to comment.