Skip to content

Commit

Permalink
feat(api): AppService
Browse files Browse the repository at this point in the history
- rename app.locals.configs to app.locals.paths
- load custom config use fileStrategy from yaml config in app.locals
  • Loading branch information
danny-avila committed Jan 9, 2024
1 parent fd9b1a3 commit 5664303
Show file tree
Hide file tree
Showing 9 changed files with 48 additions and 22 deletions.
1 change: 1 addition & 0 deletions api/config/paths.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const path = require('path');

module.exports = {
dist: path.resolve(__dirname, '..', '..', 'client', 'dist'),
publicPath: path.resolve(__dirname, '..', '..', 'client', 'public'),
imageOutput: path.resolve(__dirname, '..', '..', 'client', 'public', 'images'),
};
29 changes: 12 additions & 17 deletions api/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,42 +5,37 @@ const cors = require('cors');
const express = require('express');
const passport = require('passport');
const mongoSanitize = require('express-mongo-sanitize');
const { initializeFirebase } = require('~/server/services/Files/Firebase/initialize');
const loadCustomConfig = require('~/server/services/Config/loadCustomConfig');
const errorController = require('~/server/controllers/ErrorController');
const configureSocialLogins = require('~/server/socialLogins');
const noIndex = require('~/server/middleware/noIndex');
const { connectDb, indexSync } = require('~/lib/db');
const { logger } = require('~/config');
const errorController = require('./controllers/ErrorController');
const { jwtLogin, passportLogin } = require('../strategies');
const configureSocialLogins = require('./socialLogins');
const { connectDb, indexSync } = require('../lib/db');
const AppService = require('./services/AppService');
const noIndex = require('./middleware/noIndex');
const { logger } = require('../config');

const routes = require('~/server/routes');
const paths = require('~/config/paths');
const routes = require('./routes');

const { PORT, HOST, ALLOW_SOCIAL_LOGIN } = process.env ?? {};

const port = Number(PORT) || 3080;
const host = HOST || 'localhost';
const projectPath = path.join(__dirname, '..', '..', 'client');
const { jwtLogin, passportLogin } = require('~/strategies');

const startServer = async () => {
await connectDb();
logger.info('Connected to MongoDB');
await loadCustomConfig();
initializeFirebase();
await indexSync();

const app = express();
app.locals.config = paths;
await AppService(app);

// Middleware
app.use(noIndex);
app.use(errorController);
app.use(express.json({ limit: '3mb' }));
app.use(mongoSanitize());
app.use(express.urlencoded({ extended: true, limit: '3mb' }));
app.use(express.static(path.join(projectPath, 'dist')));
app.use(express.static(path.join(projectPath, 'public')));
app.use(express.static(app.locals.paths.dist));
app.use(express.static(app.locals.paths.publicPath));
app.set('trust proxy', 1); // trust first proxy
app.use(cors());

Expand Down Expand Up @@ -81,7 +76,7 @@ const startServer = async () => {
app.use('/api/files', routes.files);

app.use((req, res) => {
res.status(404).sendFile(path.join(projectPath, 'dist', 'index.html'));
res.status(404).sendFile(path.join(app.locals.paths.dist, 'index.html'));
});

app.listen(port, host, () => {
Expand Down
2 changes: 1 addition & 1 deletion api/server/routes/files/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const isValidPath = (req, base, subfolder, filepath) => {
};

const deleteFile = async (req, file) => {
const { publicPath } = req.app.locals.config;
const { publicPath } = req.app.locals.paths;
const parts = file.filepath.split(path.sep);
const subfolder = parts[1];
const filepath = path.join(publicPath, file.filepath);
Expand Down
2 changes: 1 addition & 1 deletion api/server/routes/files/multer.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const sizeLimit = 20 * 1024 * 1024; // 20 MB

const storage = multer.diskStorage({
destination: function (req, file, cb) {
const outputPath = path.join(req.app.locals.config.imageOutput, 'temp');
const outputPath = path.join(req.app.locals.paths.imageOutput, 'temp');
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true });
}
Expand Down
26 changes: 26 additions & 0 deletions api/server/services/AppService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const { FileSources } = require('librechat-data-provider');
const { initializeFirebase } = require('./Files/Firebase/initialize');
const loadCustomConfig = require('./Config/loadCustomConfig');
const paths = require('~/config/paths');

/**
*
* Loads custom config and initializes app-wide variables.
* @function AppService
* @param {Express.Application} app - The Express application object.
*/
const AppService = async (app) => {
const config = (await loadCustomConfig()) ?? {};
const fileStrategy = config.CDN_PROVIDER ?? FileSources.local;

if (fileStrategy === FileSources.firebase) {
initializeFirebase();
}

app.locals = {
fileStrategy,
paths,
};
};

module.exports = AppService;
2 changes: 1 addition & 1 deletion api/server/services/Files/images/convert.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ async function convertToWebP(req, file, resolution = 'high') {
const { buffer: resizedBuffer, width, height } = await resizeImage(inputFilePath, resolution);
const extension = path.extname(inputFilePath);

const { imageOutput } = req.app.locals.config;
const { imageOutput } = req.app.locals.paths;
const userPath = path.join(imageOutput, req.user.id);

if (!fs.existsSync(userPath)) {
Expand Down
2 changes: 1 addition & 1 deletion api/server/services/Files/images/encode.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function encodeImage(imagePath) {
* @returns {Promise<[MongoFile, string]>} - A promise that resolves to an array of results from updateFile and encodeImage.
*/
async function updateAndEncode(req, file) {
const { publicPath, imageOutput } = req.app.locals.config;
const { publicPath, imageOutput } = req.app.locals.paths;
const userPath = path.join(imageOutput, req.user.id);

if (!fs.existsSync(userPath)) {
Expand Down
2 changes: 1 addition & 1 deletion api/server/services/Files/save.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async function saveFile(file, outputPath, outputFilename) {
* @throws Will throw an error if the image saving process fails.
*/
const saveLocalImage = async (req, file, filename) => {
const imagePath = req.app.locals.config.imageOutput;
const imagePath = req.app.locals.paths.imageOutput;
const outputPath = path.join(imagePath, req.user.id ?? '');
await saveFile(file, outputPath, filename);
};
Expand Down
4 changes: 4 additions & 0 deletions api/server/socialLogins.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ const {
} = require('../strategies');
const client = require('../cache/redis');

/**
*
* @param {Express.Application} app
*/
const configureSocialLogins = (app) => {
if (process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET) {
passport.use(googleLogin());
Expand Down

0 comments on commit 5664303

Please sign in to comment.