Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor/Lambda #21

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 16 additions & 15 deletions .env.sample
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
PORT=YOUR_POTR_NUMBER
# DB
DB_CONNECTION = DB_CONNECTION
DB_USERNAME = DB_USERNAME
DB_PASSWORD = DB_PASSWORD
DB_LOGGING = DB_LOGGING

DB_CONNECTION=CONNECTION
DB_HOST=HOST
DB_USERNAME=USERNAME
DB_PASSWORD=PASSWORD
DB_DATABASE=DATABASENAME
DB_PORT=PROT
DB_LOGGING=LOGGING
DB_HOST = DB_HOST
DB_DATABASE = DB_DATABASE
DB_PORT = DB_PORT
DATABASE_URL = DATABASE_URL

DATABASE_URL=URL

SECRET_KEY=SECRET_KEY
PORT = PORT
SECRET_KEY = SECRET_KEY

# AWS-S3
AWS_ACCESS_KEY_ID=AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY=AWS_SECRET_ACCESS_KEY
AWS_S3_REGION=AWS_S3_REGION
AWS_S3_BUCKET_NAME=AWS_S3_BUCKET_NAME
AWS_ACCESS_KEY_ID = AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY = AWS_SECRET_ACCESS_KEY
S3_REGION = S3_REGION
BUCKET_NAME = BUCKET_NAME

API_ENDPOINT=API_ENDPOINT
META_DATA_URL = META_DATA_URL
28 changes: 18 additions & 10 deletions app.js → index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const serverless = require("serverless-http"); // Lambda

Comment on lines +1 to +2
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

app.js에서 index.js로 변경하였습니다.

app.js로 사용해도 상관없는데, 그냥 핸들러의 default가 index이기에 바꿨습니다.
스크린샷 2023-11-04 오후 7 52 07

app.js로 사용하면 app.handler로 수정하면 돼요!

const dotenv = require("dotenv");

const express = require("express");
Expand All @@ -10,31 +12,37 @@ const dataSource = require("./models/appDataSource");
const routes = require("./routes");
const baseResponse = require("./utils/baseResponse");

dataSource
.initialize()
.then(() => {
const initializeDataSource = async () => {
try {
await dataSource.initialize();
console.log("Data Source has been initialized!");
})
.catch((error) => {
console.err(`Initialize Error ${error}`);
});
} catch (error) {
console.error(`Initialize Error: ${error}`);
}
};

// 데이터 소스를 즉시 초기화하려는 경우 여기서 호출
initializeDataSource();

const app = express();

app.use(express.json());
app.use(cors());
app.use(morgan("dev"));
app.use(routes);
app.use(baseResponse);

app.get("/ping", (req, res) => {
return res.status(200).json({ message: "pong" });
});
// app.get("/", (req, res) => {
// return res.status(200).json({ message: "Welcome to the API" });
// });

const PORT = process.env.PORT;

const start = async () => {
app.listen(PORT, () => console.log(`server is listening on ${PORT}`));
};

start();
start();

module.exports.handler = serverless(app);
Comment on lines +47 to +48
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

module.exports.handler = serverless(app);

AWS Lambda와 같은 서버리스 환경에서 Express.js 애플리케이션을 실행하기 위해 필요해요!

npm install serverless-http로 꼭 install 먼저 해주세요!

2 changes: 1 addition & 1 deletion models/community/controller/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class CommunityController {
try {
const { id } = req.params;
const result = await this.communityService.findPost(id);
console.log(res);

baseResponse({ result }, res);
} catch (err) {
next(err);
Expand Down
184 changes: 92 additions & 92 deletions models/community/service/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,46 +4,44 @@ const { deleteImageFromS3 } = require("../../../utils/s3/imageUploader");
const CustomException = require("../../../utils/handler/customException");
const { DATABASE_ERROR } = require("../../../utils/baseResponseStatus");


class CommunityService{
async createPost(data){
try{
await dataSource.query(
`
class CommunityService {
async createPost(data) {
try {
await dataSource.query(
`
INSERT INTO community(
title,
content,
user_id
) VALUES (?, ?, ?)
`,
[data.title, data.content, data.user_id]
);
if(data.community_image_url !== 'null'){
const community_id = await dataSource.query(
`
[data.title, data.content, data.user_id]
);
if (data.community_image_url !== "null") {
const community_id = await dataSource.query(
`
SELECT id FROM community WHERE title = ? AND content = ? AND user_id = ?
`,
[data.title,data.content,data.user_id]
);
await dataSource.query(
`INSERT INTO community_images(
[data.title, data.content, data.user_id]
);
await dataSource.query(
`INSERT INTO community_images(
community_id,
user_id,
community_image_url
)VALUES(?,?,?)`,
[community_id[0].id,data.user_id,data.community_image_url]
);
}
}catch(err){
throw new CustomException(DATABASE_ERROR);
}

};
[community_id[0].id, data.user_id, data.community_image_url]
);
}
} catch (err) {
throw new CustomException(DATABASE_ERROR);
}
}

async findPost(post_id){
try{
const result = await dataSource.query(
`
async findPost(post_id) {
try {
const result = await dataSource.query(
`
SELECT
c.id AS community_id,
c.title AS community_title,
Expand All @@ -58,21 +56,21 @@ class CommunityService{
community_images ci ON c.id = ci.community_id
WHERE
c.id = ?
`,[post_id]
);

return result;
}catch(err){
throw new CustomException(DATABASE_ERROR);
};
};
`,
[post_id]
);

async findPosts(page){
try{
console.log(1);
const offset = (page - 1) * 10;
const result = await dataSource.query(
`
return result;
} catch (err) {
throw new CustomException(DATABASE_ERROR);
}
}

async findPosts(page) {
try {
const offset = (page - 1) * 10;
const result = await dataSource.query(
`
SELECT
c.id AS community_id,
c.title AS community_title,
Expand All @@ -87,69 +85,71 @@ class CommunityService{
community_images ci ON c.id = ci.community_id
WHERE
c.id BETWEEN ? AND ?
`,[offset+1,offset+10]
);
return result;
}catch(err){
throw new CustomException(DATABASE_ERROR);
};

};
// 이걸 하나의 transaction으로 처리할 필요가 있음
async deletePost(post_id){
const queryRunner = await dataSource.createQueryRunner();
await queryRunner.startTransaction();
try{
const s3Image = await queryRunner.manager.query(
`SELECT * FROM community_images WHERE community_id = ?`,[post_id]
);
if(s3Image.length !== 0) {
await deleteImageFromS3(s3Image[0].community_image_url);
await queryRunner.manager.query(
`
`,
[offset + 1, offset + 10]
);
return result;
} catch (err) {
throw new CustomException(DATABASE_ERROR);
}
}
// 이걸 하나의 transaction으로 처리할 필요가 있음
async deletePost(post_id) {
const queryRunner = await dataSource.createQueryRunner();
await queryRunner.startTransaction();
try {
const s3Image = await queryRunner.manager.query(
`SELECT * FROM community_images WHERE community_id = ?`,
[post_id]
);
if (s3Image.length !== 0) {
await deleteImageFromS3(s3Image[0].community_image_url);
await queryRunner.manager.query(
`
DELETE ci
FROM community_images ci
WHERE ci.community_id = ?
`,
[post_id]
);
}
await queryRunner.manager.query(
`
[post_id]
);
}
await queryRunner.manager.query(
`
DELETE c
FROM community c
WHERE c.id = ?
`,
[post_id]
);
await queryRunner.commitTransaction();
}catch(err){
await queryRunner.rollbackTransaction();
throw new CustomException(DATABASE_ERROR);
};
};
[post_id]
);
await queryRunner.commitTransaction();
} catch (err) {
await queryRunner.rollbackTransaction();
throw new CustomException(DATABASE_ERROR);
}
}

async updatePost(post_id, data){
try{
const s3Image = await dataSource.query(
`SELECT * FROM community_images WHERE community_id = ?`,[post_id]
);
if(s3Image.length !== 0) {
await deleteImageFromS3(s3Image[0].community_image_url);
}
await dataSource.query(
`
async updatePost(post_id, data) {
try {
const s3Image = await dataSource.query(
`SELECT * FROM community_images WHERE community_id = ?`,
[post_id]
);
if (s3Image.length !== 0) {
await deleteImageFromS3(s3Image[0].community_image_url);
}
await dataSource.query(
`
UPDATE community c
LEFT JOIN community_images ci ON c.id = ci.community_id
SET c.title = ?,c.content = ? , ci.community_image_url = ?
WHERE c.id = ?;
`,
[data.title,data.content,data.community_image_url,post_id]
);
}catch(err){
throw new CustomException(DATABASE_ERROR);
};
};
};
[data.title, data.content, data.community_image_url, post_id]
);
} catch (err) {
throw new CustomException(DATABASE_ERROR);
}
}
}

module.exports = CommunityService;
module.exports = CommunityService;
3 changes: 0 additions & 3 deletions models/publicData/publicDataController.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ const createPost = async (req, res) => {
cost,
1
);

return baseResponse({ postId: `${postId.insertId}` }, res);
} catch (error) {
console.log(error);
Expand Down Expand Up @@ -58,7 +57,6 @@ const getAllposts = async (req, res) => {

return baseResponse({ headInfo, rows }, res);
} catch (error) {
console.log(error);
return baseResponse(error, res);
}
};
Expand Down Expand Up @@ -86,7 +84,6 @@ const updatePost = async (req, res) => {
url,
cost
);

return baseResponse({ id: id, info: result.info }, res);
} catch (error) {
console.log(error);
Expand Down
2 changes: 0 additions & 2 deletions models/user/service/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ class UserService {
const queryRunner = await dataSource.createQueryRunner();
await queryRunner.startTransaction();
try {
console.log(id);
await queryRunner.manager.query(
`
DELETE u
Expand All @@ -73,7 +72,6 @@ class UserService {
`,
[id]
);
console.log(id);
await queryRunner.commitTransaction();
//await queryRunner.release();
} catch (err) {
Expand Down
Loading