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

chore: change using only express to serve app #410

Open
wants to merge 1 commit into
base: develop
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
9 changes: 0 additions & 9 deletions .firebaserc

This file was deleted.

8 changes: 0 additions & 8 deletions firebase.json

This file was deleted.

70 changes: 42 additions & 28 deletions functions/api/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const dotenv = require("dotenv");
const hpp = require("hpp");
const helmet = require("helmet");
const util = require("../lib/util");
const admin = require("firebase-admin");
const prodServiceAccount = require("../nadosunbae-server-firebase-adminsdk-lzgu9-7c653db78a");
const devServiceAccount = require("../nadosunbae-server-dev-90ac3-firebase-adminsdk-r7b4s-10d004f02b");
const logger = require("morgan");

// use .env for security
dotenv.config();
Expand All @@ -24,40 +28,50 @@ if (process.env.NODE_ENV === "production" || process.env.NODE_ENV === "developme
}

// parse requests to json
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

// req logging
const reqLogger = (req, res, next) => {
console.log(
"\n\n",
"[api]",
`[${req.method.toUpperCase()}]`,
req.originalUrl,
`[${req.method}] ${!!req.user ? `${req.user.id}` : ``} ${req.originalUrl}\n ${
!!req.query && `query: ${JSON.stringify(req.query)}`
} ${!!req.params && `params ${JSON.stringify(req.params)}`}`,
);

next();
};

// routing with routes directory
app.use("/", require("./routes"));
app.use("/api", reqLogger, require("./routes"));

// path not found
app.use("*", (req, res) => {
res.status(404).json({
status: 404,
success: false,
message: "잘못된 경로입니다.",
});
res.status(404).send(util.fail(404, "잘못된 경로입니다."));
});

// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};

// render the error page
res.status(err.status || 500);
res.render("error");
});

const serviceAccount =
process.env.NODE_ENV === "production" ? prodServiceAccount : devServiceAccount;

admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});

// for firebase functions
module.exports = functions
.runWith({
timeoutSeconds: 300, // 300 sec for processing request
memory: "512MB",
})
.region("asia-northeast3") // seoul
.https.onRequest(async (req, res) => {
// for debugging
console.log(
"\n\n",
"[api]",
`[${req.method.toUpperCase()}]`,
req.originalUrl,
`[${req.method}] ${!!req.user ? `${req.user.id}` : ``} ${req.originalUrl}\n ${
!!req.query && `query: ${JSON.stringify(req.query)}`
} ${!!req.params && `params ${JSON.stringify(req.params)}`}`,
);

return app(req, res);
});
module.exports = app;
11 changes: 2 additions & 9 deletions functions/db/db.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
const functions = require("firebase-functions");
const { Pool, Query } = require("pg");
const dayjs = require("dayjs");
const dotenv = require("dotenv");
Expand Down Expand Up @@ -49,14 +48,8 @@ const connect = async (req) => {
const release = client.release;

const releaseChecker = setTimeout(() => {
localMode
? console.error("[ERROR] client connection이 15초 동안 릴리즈되지 않았습니다.", { callStack })
: functions.logger.error("[ERROR] client connection이 15초 동안 릴리즈되지 않았습니다.", {
callStack,
});
localMode
? console.error(`마지막으로 실행된 쿼리문입니다. ${client.lastQuery}`)
: functions.logger.error(`마지막으로 실행된 쿼리문입니다. ${client.lastQuery}`);
console.error("[ERROR] client connection이 15초 동안 릴리즈되지 않았습니다.", { callStack });
console.error(`마지막으로 실행된 쿼리문입니다. ${client.lastQuery}`);
}, 15 * 1000);

client.query = (...args) => {
Expand Down
73 changes: 53 additions & 20 deletions functions/index.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,55 @@
const admin = require("firebase-admin");
const prodServiceAccount = require("./nadosunbae-server-firebase-adminsdk-lzgu9-7c653db78a");
const devServiceAccount = require("./nadosunbae-server-dev-90ac3-firebase-adminsdk-r7b4s-10d004f02b");
const dotenv = require("dotenv");

dotenv.config();

const serviceAccount =
process.env.NODE_ENV === "production" ? prodServiceAccount : devServiceAccount;

let firebase;
if (admin.apps.length === 0) {
firebase = admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
} else {
firebase = admin.app();
const app = require("./api/index");
const debug = require("debug")("express:server");
const http = require("http");

const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);

const server = http.createServer(app);

server.listen(port);
server.on("error", onError);
server.on("listening", onListening);

function normalizePort(val) {
var port = parseInt(val, 10);

if (isNaN(port)) {
return val;
}

if (port >= 0) {
return port;
}

return false;
}

function onError(error) {
if (error.syscall !== "listen") {
throw error;
}

var bind = typeof port === "string" ? "Pipe " + port : "Port " + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
}

module.exports = {
api: require("./api"),
};
function onListening() {
var addr = server.address();
var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
debug("Listening on " + bind);
console.log("Listening on " + bind);
}
Loading