Skip to content

Commit

Permalink
feat(prettier): Missing Config (#17)
Browse files Browse the repository at this point in the history
* feat(prettier): Missing Config

* style(prettier)

* style(prettier)
  • Loading branch information
Kathund authored Dec 17, 2023
1 parent 1be595b commit 7b86741
Show file tree
Hide file tree
Showing 10 changed files with 87 additions and 96 deletions.
6 changes: 1 addition & 5 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@
"es2021": true,
"node": true
},
"extends": [
"plugin:@typescript-eslint/recommended",
"eslint:recommended",
"plugin:import/recommended"
],
"extends": ["plugin:@typescript-eslint/recommended", "eslint:recommended", "plugin:import/recommended"],
"parserOptions": { "ecmaVersion": "latest" },
"overrides": [],
"rules": {
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci-cd-16x.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ on:
workflow_dispatch:

env:
NODE_VERSION: "16.x"
NODE_VERSION: '16.x'

jobs:
prettier:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci-cd-18x.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ on:
workflow_dispatch:

env:
NODE_VERSION: "18.x"
NODE_VERSION: '18.x'

jobs:
prettier:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci-cd-20x.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ on:
workflow_dispatch:

env:
NODE_VERSION: "20.x"
NODE_VERSION: '20.x'

jobs:
prettier:
Expand Down
9 changes: 9 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"bracketSameLine": true,
"arrowParens": "always",
"trailingComma": "es5",
"bracketSpacing": true,
"singleQuote": true,
"printWidth": 120,
"tabWidth": 2
}
22 changes: 10 additions & 12 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { errorMessage, otherMessage } from "./src/logger";
import { loadEndpoints } from "./src/helper";
import fileUpload from "express-fileupload";
import { existsSync, mkdirSync } from "fs";
import { PORT } from "./config.json";
import express from "express";
import { join } from "path";
import { errorMessage, otherMessage } from './src/logger';
import { loadEndpoints } from './src/helper';
import fileUpload from 'express-fileupload';
import { existsSync, mkdirSync } from 'fs';
import { PORT } from './config.json';
import express from 'express';
import { join } from 'path';

const filesDir = join(__dirname, "src", "files");
const filesDir = join(__dirname, 'src', 'files');
if (!existsSync(filesDir)) {
mkdirSync(filesDir);
}
Expand All @@ -16,12 +16,10 @@ const app = express();
try {
app.use(fileUpload());

const endpointsDir = join(__dirname, "src", "endpoints");
const endpointsDir = join(__dirname, 'src', 'endpoints');
const result = loadEndpoints(endpointsDir, app);
if (result !== undefined) {
otherMessage(
`Loaded ${result.loaded} endpoints, skipped ${result.skipped} endpoints`,
);
otherMessage(`Loaded ${result.loaded} endpoints, skipped ${result.skipped} endpoints`);
} else {
otherMessage(`No endpoints found in ${endpointsDir}`);
}
Expand Down
22 changes: 9 additions & 13 deletions src/endpoints/file.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,28 @@
import { Application, Request, Response } from "express";
import { apiMessage, errorMessage } from "../logger";
import { existsSync } from "fs";
import { resolve } from "path";
import { Application, Request, Response } from 'express';
import { apiMessage, errorMessage } from '../logger';
import { existsSync } from 'fs';
import { resolve } from 'path';

export default (app: Application) => {
app.get("/:name", async (req: Request, res: Response) => {
app.get('/:name', async (req: Request, res: Response) => {
try {
const fileName = req.params.name;
apiMessage(req.path, `User is trying to get a file - ${fileName}`);
const fileNamePattern = /^[a-zA-Z0-9_-]+$/;
if (!fileNamePattern.test(fileName)) {
return res.status(400).json({ error: "Invalid file name" });
return res.status(400).json({ error: 'Invalid file name' });
}
const filePath = resolve(__dirname, "../", "files", fileName);
const filePath = resolve(__dirname, '../', 'files', fileName);
if (!existsSync(filePath)) {
errorMessage(`File ${fileName} not found`);
return res
.status(404)
.send({ sucsess: false, message: `File ${fileName} not found` });
return res.status(404).send({ sucsess: false, message: `File ${fileName} not found` });
}

apiMessage(req.path, `File ${fileName} found`);
return res.sendFile(filePath);
} catch (err) {
errorMessage(err as string);
return res
.status(500)
.send({ sucsess: false, message: "Internal server error" });
return res.status(500).send({ sucsess: false, message: 'Internal server error' });
}
});
};
42 changes: 17 additions & 25 deletions src/endpoints/save.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,35 @@
import { Application, Request, Response } from "express";
import { apiMessage, errorMessage } from "../logger";
import { UploadedFile } from "express-fileupload";
import { url, key } from "../../config.json";
import { existsSync } from "fs";
import { join } from "path";
import { Application, Request, Response } from 'express';
import { apiMessage, errorMessage } from '../logger';
import { UploadedFile } from 'express-fileupload';
import { url, key } from '../../config.json';
import { existsSync } from 'fs';
import { join } from 'path';

export default (app: Application) => {
app.post("/save/:name", async (req: Request, res: Response) => {
app.post('/save/:name', async (req: Request, res: Response) => {
try {
const apiKey = req.headers["API-KEY"];
const apiKey = req.headers['API-KEY'];
if (apiKey !== key) {
errorMessage("Invalid API key provided");
return res
.status(400)
.send({ sucsess: false, message: "Invalid API key" });
errorMessage('Invalid API key provided');
return res.status(400).send({ sucsess: false, message: 'Invalid API key' });
}
apiMessage(req.path, "User is trying to save a file");
apiMessage(req.path, 'User is trying to save a file');

const file = req.files?.file as UploadedFile;
if (!file) {
errorMessage("No file provided for upload");
return res
.status(400)
.send({ sucsess: false, message: "No file provided" });
errorMessage('No file provided for upload');
return res.status(400).send({ sucsess: false, message: 'No file provided' });
}

const fileName = req.params.name;
const fileNamePattern = /^[a-zA-Z0-9_-]+$/;
if (!fileNamePattern.test(fileName)) {
return res.status(400).json({ error: "Invalid file name" });
return res.status(400).json({ error: 'Invalid file name' });
}
const filePath = join(__dirname, "../", "files", fileName);
const filePath = join(__dirname, '../', 'files', fileName);
if (existsSync(filePath)) {
errorMessage(`File ${fileName} already exists`);
return res
.status(400)
.json({ sucsess: false, message: `File ${fileName} already exists` });
return res.status(400).json({ sucsess: false, message: `File ${fileName} already exists` });
}

await file.mv(filePath);
Expand All @@ -47,9 +41,7 @@ export default (app: Application) => {
});
} catch (err) {
errorMessage(err as string);
return res
.status(500)
.json({ sucsess: false, message: "Internal server error" });
return res.status(500).json({ sucsess: false, message: 'Internal server error' });
}
});
};
14 changes: 7 additions & 7 deletions src/helper.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { otherMessage, errorMessage } from "./logger";
import { readdirSync, statSync } from "fs";
import { Application } from "express";
import { basename, join } from "path";
import { otherMessage, errorMessage } from './logger';
import { readdirSync, statSync } from 'fs';
import { Application } from 'express';
import { basename, join } from 'path';

export const loadEndpoints = (directory: string, app: Application) => {
try {
Expand All @@ -19,16 +19,16 @@ export const loadEndpoints = (directory: string, app: Application) => {
skipped += result.skipped;
loaded += result.loaded;
}
} else if (item.toLowerCase().endsWith(".ts")) {
if (item.toLowerCase().includes("disabled")) {
} else if (item.toLowerCase().endsWith('.ts')) {
if (item.toLowerCase().includes('disabled')) {
skipped++;
continue;
}
(async () => {
loaded++;
const route = await import(itemPath);
route(app);
otherMessage(`Loaded ${basename(itemPath).split(".ts")[0]} endpoint`);
otherMessage(`Loaded ${basename(itemPath).split('.ts')[0]} endpoint`);
})();
}
}
Expand Down
62 changes: 31 additions & 31 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,106 +1,106 @@
const customLevels = { api: 0, error: 1, warn: 2, other: 3, max: 4 };
import { createLogger, format, transports } from "winston";
import { createLogger, format, transports } from 'winston';

const timezone = () => {
return new Date().toLocaleString("en-US", {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
return new Date().toLocaleString('en-US', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
});
};

const apiTransport = new transports.File({
level: "api",
filename: "./logs/api.log",
level: 'api',
filename: './logs/api.log',
});

const errorTransport = new transports.File({
level: "error",
filename: "./logs/error.log",
level: 'error',
filename: './logs/error.log',
});

const warnTransport = new transports.File({
level: "warn",
filename: "./logs/warn.log",
level: 'warn',
filename: './logs/warn.log',
});

const otherTransport = new transports.File({
level: "other",
filename: "./logs/other.log",
level: 'other',
filename: './logs/other.log',
});

const combinedTransport = new transports.File({
level: "max",
filename: "./logs/combined.log",
level: 'max',
filename: './logs/combined.log',
});

const consoleTransport = new transports.Console({
level: "max",
level: 'max',
});

const apiLogger = createLogger({
level: "api",
level: 'api',
levels: customLevels,
format: format.combine(
format.timestamp({ format: timezone }),
format.printf(({ timestamp, level, message }) => {
return `[${timestamp}] ${level.toUpperCase()} > ${message}`;
}),
})
),
transports: [apiTransport, combinedTransport, consoleTransport],
});

const errorLogger = createLogger({
level: "error",
level: 'error',
levels: customLevels,
format: format.combine(
format.timestamp({ format: timezone }),
format.printf(({ timestamp, level, message }) => {
return `[${timestamp}] ${level.toUpperCase()} > ${message}`;
}),
})
),
transports: [errorTransport, combinedTransport, consoleTransport],
});

const warnLogger = createLogger({
level: "warn",
level: 'warn',
levels: customLevels,
format: format.combine(
format.timestamp({ format: timezone }),
format.printf(({ timestamp, level, message }) => {
return `[${timestamp}] ${level.toUpperCase()} > ${message}`;
}),
})
),
transports: [warnTransport, combinedTransport, consoleTransport],
});

const otherLogger = createLogger({
level: "other",
level: 'other',
levels: customLevels,
format: format.combine(
format.timestamp({ format: timezone }),
format.printf(({ timestamp, level, message }) => {
return `[${timestamp}] ${level.toUpperCase()} > ${message}`;
}),
})
),
transports: [otherTransport, combinedTransport, consoleTransport],
});
const logger = {
api: (endPoint: string, message: string) => {
apiLogger.log("api", `${endPoint} | ${message}`);
apiLogger.log('api', `${endPoint} | ${message}`);
},
error: (message: string) => {
errorLogger.log("error", message);
errorLogger.log('error', message);
},
warn: (message: string) => {
warnLogger.log("warn", message);
warnLogger.log('warn', message);
},
other: (message: string) => {
otherLogger.log("other", message);
otherLogger.log('other', message);
},
};

Expand Down

0 comments on commit 7b86741

Please sign in to comment.