Skip to content

Commit

Permalink
style(prettier)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kathund committed Dec 17, 2023
1 parent 5a69642 commit b3b4edd
Show file tree
Hide file tree
Showing 11 changed files with 83 additions and 101 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
12 changes: 6 additions & 6 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
name: 'CodeQL'

on:
push:
branches: ["main"]
branches: ['main']
pull_request:
# The branches below must be a subset of the branches above
branches: ["main"]
branches: ['main']
schedule:
- cron: "30 12 * * *"
- cron: '30 12 * * *'

jobs:
analyze:
Expand All @@ -38,7 +38,7 @@ jobs:
strategy:
fail-fast: false
matrix:
language: ["javascript-typescript"]
language: ['javascript-typescript']
# CodeQL supports [ 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift' ]
# Use only 'java-kotlin' to analyze code written in Java, Kotlin or both
# Use only 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
Expand Down Expand Up @@ -78,4 +78,4 @@ jobs:
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
category: '/language:${{matrix.language}}'
2 changes: 1 addition & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
"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
20 changes: 8 additions & 12 deletions src/endpoints/file.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,24 @@
import { Application, Request, Response } from "express";
import { apiMessage, errorMessage } from "../logger";
import { existsSync } from "fs";
import { join } from "path";
import { Application, Request, Response } from 'express';
import { apiMessage, errorMessage } from '../logger';
import { existsSync } from 'fs';
import { join } 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 filePath = join(__dirname, "../", "files", fileName);
const filePath = join(__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' });
}
});
};
40 changes: 16 additions & 24 deletions src/endpoints/save.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,31 @@
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 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 @@ -43,9 +37,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 b3b4edd

Please sign in to comment.