Skip to content

Commit

Permalink
Revert "Fix: loadenv 를 As-Is에서 사용하던 Nested object로 변경하였습니다"
Browse files Browse the repository at this point in the history
This reverts commit 7e17d5f.
  • Loading branch information
kmc7468 committed Nov 19, 2024
1 parent 0d61e46 commit d90f28c
Show file tree
Hide file tree
Showing 14 changed files with 92 additions and 95 deletions.
2 changes: 1 addition & 1 deletion scripts/profileImageUrlUpdater.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// https://github.com/sparcs-kaist/taxi-back/issues/173

const { MongoClient } = require("mongodb");
const { mongoUrl, aws: awsEnv } = require("../loadenv"); // FIXME: 올바른 경로로 수정해야 합니다.
const { mongo: mongoUrl, aws: awsEnv } = require("../loadenv"); // FIXME: 올바른 경로로 수정해야 합니다.

const time = Date.now();

Expand Down
10 changes: 5 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import express from "express";
import cookieParser from "cookie-parser";
import http from "http";

import config from "@/loadenv";
import { nodeEnv, mongo as mongoUrl, port as httpPort } from "@/loadenv";
import {
corsMiddleware,
sessionMiddleware,
Expand Down Expand Up @@ -40,14 +40,14 @@ initializeApp();
const app = express();

// 데이터베이스 연결
connectDatabase(config.mongoUrl);
connectDatabase(mongoUrl);

// [Middleware] request body 파싱
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// reverse proxy가 설정한 헤더를 신뢰합니다.
if (config.nodeEnv === "production") app.set("trust proxy", 2);
if (nodeEnv === "production") app.set("trust proxy", 2);

// [Middleware] CORS 설정
app.use(corsMiddleware);
Expand Down Expand Up @@ -95,8 +95,8 @@ app.use(errorHandler);
// express 서버 시작
const serverHttp = http
.createServer(app)
.listen(config.port, () =>
logger.info(`Express server started from port ${config.port}`)
.listen(httpPort, () =>
logger.info(`Express server started from port ${httpPort}`)
);

// socket.io 서버 시작
Expand Down
98 changes: 47 additions & 51 deletions src/loadenv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import dotenv from "dotenv";
import { type Algorithm } from "jsonwebtoken";
import { type ServiceAccount } from "firebase-admin";
import exp from "constants";

if (process.env.NODE_ENV === undefined) {
// logger.ts가 아직 초기화되지 않았으므로 console.error를 사용합니다.
Expand All @@ -19,55 +18,52 @@ if (process.env.DB_PATH === undefined) {
process.exit(1);
}

const config = {
nodeEnv: process.env.NODE_ENV,
mongoUrl: process.env.DB_PATH,
session: {
secret: process.env.SESSION_KEY || "TAXI_SESSION_KEY",
expiry: 14 * 24 * 3600 * 1000,
},
redisUrl: process.env.REDIS_PATH,
sparcssso: {
id: process.env.SPARCSSSO_CLIENT_ID || "",
key: process.env.SPARCSSSO_CLIENT_KEY || "",
},
port: process.env.PORT ? parseInt(process.env.PORT) : 80,
corsWhiteList: (process.env.CORS_WHITELIST &&
(JSON.parse(process.env.CORS_WHITELIST) as string[])) || [true],
aws: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID as string,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string,
s3BucketName: process.env.AWS_S3_BUCKET_NAME as string,
s3Url:
process.env.AWS_S3_URL ||
`https://${process.env.AWS_S3_BUCKET_NAME}.s3.ap-northeast-2.amazonaws.com`,
},
jwt: {
secretKey: process.env.JWT_SECRET || "TAXI_JWT_KEY",
option: {
algorithm: "HS256" as Algorithm,
// FIXME: remove FRONT_URL from issuer. 단, issuer를 변경하면 이전에 발급했던 모든 JWT가 무효화됩니다.
// See https://github.com/sparcs-kaist/taxi-back/issues/415
issuer: process.env.FRONT_URL || "http://localhost:3000",
},
TOKEN_EXPIRED: -3,
TOKEN_INVALID: -2,
},

googleApplicationCredentials:
process.env.GOOGLE_APPLICATION_CREDENTIALS &&
(JSON.parse(process.env.GOOGLE_APPLICATION_CREDENTIALS) as ServiceAccount),
testAccounts:
(process.env.TEST_ACCOUNTS &&
(JSON.parse(process.env.TEST_ACCOUNTS) as string[])) ||
[],
slackWebhookUrl: {
report: process.env.SLACK_REPORT_WEBHOOK_URL || "",
},
naverMap: {
apiId: process.env.NAVER_MAP_API_ID || "",
apiKey: process.env.NAVER_MAP_API_KEY || "",
export const nodeEnv = process.env.NODE_ENV; // required ("production" or "development" or "test")
export const mongo = process.env.DB_PATH; // required
export const session = {
secret: process.env.SESSION_KEY || "TAXI_SESSION_KEY", // optional
expiry: 14 * 24 * 3600 * 1000, // 14일, ms 단위입니다.
};
export const redis = process.env.REDIS_PATH; // optional
export const sparcssso = {
id: process.env.SPARCSSSO_CLIENT_ID || "", // optional
key: process.env.SPARCSSSO_CLIENT_KEY || "", // optional
};
export const port = process.env.PORT ? parseInt(process.env.PORT) : 80; // optional (default = 80)
export const corsWhiteList = (process.env.CORS_WHITELIST &&
(JSON.parse(process.env.CORS_WHITELIST) as string[])) || [true]; // optional (default = [true])
export const aws = {
accessKeyId: process.env.AWS_ACCESS_KEY_ID as string, // required
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string, // required
s3BucketName: process.env.AWS_S3_BUCKET_NAME as string, // required
s3Url:
process.env.AWS_S3_URL ||
`https://${process.env.AWS_S3_BUCKET_NAME}.s3.ap-northeast-2.amazonaws.com`, // optional
};
export const jwt = {
secretKey: process.env.JWT_SECRET_KEY || "TAXI_JWT_KEY",
option: {
algorithm: "HS256" as Algorithm,
// FIXME: remove FRONT_URL from issuer. 단, issuer를 변경하면 이전에 발급했던 모든 JWT가 무효화됩니다.
// See https://github.com/sparcs-kaist/taxi-back/issues/415
issuer: process.env.FRONT_URL || "http://localhost:3000", // optional (default = "http://localhost:3000")
},
TOKEN_EXPIRED: -3,
TOKEN_INVALID: -2,
};
export const googleApplicationCredentials =
process.env.GOOGLE_APPLICATION_CREDENTIALS &&
(JSON.parse(process.env.GOOGLE_APPLICATION_CREDENTIALS) as ServiceAccount); // optional
export const testAccounts =
(process.env.TEST_ACCOUNTS &&
(JSON.parse(process.env.TEST_ACCOUNTS) as string[])) ||
[]; // optional
export const slackWebhookUrl = {
report: process.env.SLACK_REPORT_WEBHOOK_URL || "", // optional
};
// export const eventConfig =
// process.env.EVENT_CONFIG && JSON.parse(process.env.EVENT_CONFIG); // optional
export const naverMap = {
apiId: process.env.NAVER_MAP_API_ID || "", // optional
apiKey: process.env.NAVER_MAP_API_KEY || "", // optional
};

export default config;
4 changes: 2 additions & 2 deletions src/middlewares/cors.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import cors from "cors";
import config from "@/loadenv";
import { corsWhiteList } from "@/loadenv";

const corsMiddleware = cors({
origin: config.corsWhiteList,
origin: corsWhiteList,
credentials: true,
exposedHeaders: ["Date"],
});
Expand Down
8 changes: 4 additions & 4 deletions src/middlewares/session.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import expressSession from "express-session";
import config from "@/loadenv";
import { nodeEnv, session as sessionConfig } from "@/loadenv";
import type { LoginInfo } from "@/modules/auths/login";
import sessionStore from "@/modules/stores/sessionStore";

Expand All @@ -26,14 +26,14 @@ declare module "express-session" {
}

const sessionMiddleware = expressSession({
secret: config.session.secret,
secret: sessionConfig.secret,
resave: false,
saveUninitialized: false,
store: sessionStore,
cookie: {
maxAge: config.session.expiry,
maxAge: sessionConfig.expiry,
// nodeEnv가 production일 때만 secure cookie를 사용합니다.
secure: config.nodeEnv === "production",
secure: nodeEnv === "production",
},
});

Expand Down
4 changes: 2 additions & 2 deletions src/modules/auths/jwt.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import jwt, { type SignOptions } from "jsonwebtoken";
import config from "@/loadenv";
import { jwt as jwtConfig } from "@/loadenv";

const { secretKey, option, TOKEN_EXPIRED, TOKEN_INVALID } = config.jwt;
const { secretKey, option, TOKEN_EXPIRED, TOKEN_INVALID } = jwtConfig;

type TokenType = "access" | "refresh";

Expand Down
4 changes: 2 additions & 2 deletions src/modules/auths/login.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { type Request } from "express";
import config from "@/loadenv";
import { session as sessionConfig } from "@/loadenv";
import logger from "@/modules/logger";

export interface LoginInfo {
Expand All @@ -16,7 +16,7 @@ export const getLoginInfo = (req: Request) => {
const timeFlow = Date.now() - time;
// 14일이 지난 세션에 대해서는 로그인 정보를 반환하지 않습니다.
// 세션은 새로운 요청 시 갱신되지 않습니다.
if (timeFlow > config.session.expiry) {
if (timeFlow > sessionConfig.expiry) {
return { id: undefined, sid: undefined, oid: undefined, name: undefined };
}
return { id, sid, oid, name };
Expand Down
8 changes: 3 additions & 5 deletions src/modules/fcm.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import firebaseAdmin from "firebase-admin";
import { type SendResponse, getMessaging } from "firebase-admin/messaging";
import config from "@/loadenv";
import { googleApplicationCredentials } from "@/loadenv";
import logger from "@/modules/logger";
import {
deviceTokenModel,
Expand All @@ -13,11 +13,9 @@ import { type ChatType } from "@/types/mongo";
* credential을 등록합니다.
*/
export const initializeApp = () => {
if (config.googleApplicationCredentials) {
if (googleApplicationCredentials) {
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(
config.googleApplicationCredentials
),
credential: firebaseAdmin.credential.cert(googleApplicationCredentials),
});
} else {
logger.error(
Expand Down
4 changes: 2 additions & 2 deletions src/modules/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import path from "path";
import { createLogger, format, transports } from "winston";
import DailyRotateFileTransport from "winston-daily-rotate-file";

import config from "@/loadenv";
import { nodeEnv } from "@/loadenv";

// logger에서 사용할 포맷들을 정의합니다.
const baseFormat = format.combine(
Expand Down Expand Up @@ -50,7 +50,7 @@ const consoleTransport = new transports.Console();
* @method error(message: string, callback: winston.LogCallback) - 오류 메시지를 기록하기 위해 사용합니다.
*/
const logger =
config.nodeEnv === "production"
nodeEnv === "production"
? // "production" 환경에서 사용되는 Logger 객체
createLogger({
level: "info",
Expand Down
11 changes: 5 additions & 6 deletions src/modules/slackNotification.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import axios from "axios";
import config from "@/loadenv";
import { nodeEnv, slackWebhookUrl as slackUrl } from "@/loadenv";
import logger from "@/modules/logger";
import { type Report } from "@/types/mongo";

export const sendTextToReportChannel = (text: string) => {
if (!config.slackWebhookUrl.report) return;
if (!slackUrl.report) return;

const data = {
text:
config.nodeEnv === "production" ? text : `(${config.nodeEnv}) ${text}`, // Production 환경이 아닌 경우, 환경 이름을 붙여서 전송합니다.
text: nodeEnv === "production" ? text : `(${nodeEnv}) ${text}`, // Production 환경이 아닌 경우, 환경 이름을 붙여서 전송합니다.
};
const axiosConfig = { headers: { "Content-Type": "application/json" } };
const config = { headers: { "Content-Type": "application/json" } };

axios
.post(config.slackWebhookUrl.report, data, axiosConfig)
.post(slackUrl.report, data, config)
.then(() => {
logger.info("Slack webhook sent successfully");
})
Expand Down
14 changes: 7 additions & 7 deletions src/modules/stores/aws.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import AWS from "aws-sdk";
import config from "@/loadenv";
import { aws as awsEnv } from "@/loadenv";

AWS.config.update({
region: "ap-northeast-2",
Expand All @@ -16,7 +16,7 @@ export const getList = (
) => {
s3.listObjects(
{
Bucket: config.aws.s3BucketName,
Bucket: awsEnv.s3BucketName,
Prefix: directoryPath,
},
(err, data) => {
Expand All @@ -31,7 +31,7 @@ export const getUploadPUrlPut = (
contentType: string = "image/png"
) => {
const presignedUrl = s3.getSignedUrl("putObject", {
Bucket: config.aws.s3BucketName,
Bucket: awsEnv.s3BucketName,
Key: filePath,
ContentType: contentType,
Expires: 60, // 1 min
Expand All @@ -47,7 +47,7 @@ export const getUploadPUrlPost = (
) => {
s3.createPresignedPost(
{
Bucket: config.aws.s3BucketName,
Bucket: awsEnv.s3BucketName,
Expires: 60, // 1 min
Conditions: [
{ key: filePath },
Expand All @@ -68,7 +68,7 @@ export const deleteObject = (
) => {
s3.deleteObject(
{
Bucket: config.aws.s3BucketName,
Bucket: awsEnv.s3BucketName,
Key: filePath,
},
(err, data) => {
Expand All @@ -84,7 +84,7 @@ export const foundObject = (
) => {
s3.headObject(
{
Bucket: config.aws.s3BucketName,
Bucket: awsEnv.s3BucketName,
Key: filePath,
},
(err, data) => {
Expand All @@ -95,5 +95,5 @@ export const foundObject = (

// function to return full URL of the object
export const getS3Url = (filePath: string) => {
return `${config.aws.s3Url}${filePath}`;
return `${awsEnv.s3Url}${filePath}`;
};
14 changes: 9 additions & 5 deletions src/modules/stores/sessionStore.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import MongoStore from "connect-mongo";
import RedisStore from "connect-redis";
import redis from "redis";
import config from "@/loadenv";
import {
redis as redisUrl,
mongo as mongoUrl,
session as sessionConfig,
} from "@/loadenv";
import logger from "@/modules/logger";

const getSessionStore = () => {
// 환경변수 REDIS_PATH 유무에 따라 session 저장 방식이 변경됩니다.
if (config.redisUrl) {
if (redisUrl) {
const client = redis.createClient({
url: config.redisUrl,
url: redisUrl,
});

// redis client 연결 성공 시 로그를 출력합니다.
Expand All @@ -22,9 +26,9 @@ const getSessionStore = () => {
});

client.connect().catch(logger.error);
return new RedisStore({ client, ttl: config.session.expiry });
return new RedisStore({ client, ttl: sessionConfig.expiry });
} else {
return MongoStore.create({ mongoUrl: config.mongoUrl });
return MongoStore.create({ mongoUrl });
}
};

Expand Down
2 changes: 1 addition & 1 deletion src/sampleGenerator/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const {
generateChats,
} = require("./src/testData");
const { connectDatabase } = require("../modules/stores/mongo");
const { mongoUrl, numberOfChats, numberOfRooms } = require("./loadenv");
const { mongo: mongoUrl, numberOfChats, numberOfRooms } = require("./loadenv");

const database = connectDatabase(mongoUrl);

Expand Down
Loading

0 comments on commit d90f28c

Please sign in to comment.