Skip to content

Commit

Permalink
feat: setting environment
Browse files Browse the repository at this point in the history
  • Loading branch information
PunGrumpy committed Nov 4, 2023
1 parent 4b3f10d commit 6f5e553
Show file tree
Hide file tree
Showing 8 changed files with 145 additions and 68 deletions.
25 changes: 25 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
module.exports = {
env: {
es2021: true,
node: true
},
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module'
},
plugins: ['@typescript-eslint'],
rules: {
'@typescript-eslint/ban-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'no-mixed-spaces-and-tabs': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-extra-semi': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/no-namespace': 'off',
'no-case-declarations': 'off',
'no-extra-semi': 'off'
},
ignorePatterns: ['example/*', 'tests/**/*', 'lint-staged.config.js']
}
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

bun lint
Binary file modified bun.lockb
Binary file not shown.
20 changes: 20 additions & 0 deletions lint-staged.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { existsSync } from 'fs'
import { join } from 'path'

const isBun = existsSync(join(process.cwd(), 'bun.lockb'))
const isYarn = existsSync(join(process.cwd(), 'yarn.lock'))
const isPnpm = existsSync(join(process.cwd(), 'pnpm-lock.yaml'))

const packageManager = isBun ? 'bun' : isYarn ? 'yarn' : isPnpm ? 'pnpm' : 'npm'

const options = {
'**/*.(ts|tsx)': () => `${packageManager} tsc --noEmit`,
'**/*.(ts|tsx|js)': filenames => [
`${packageManager} eslint --fix ${filenames.join(' ')}`,
`${packageManager} prettier --write ${filenames.join(' ')}`
],
'**/*.(md|json)': filenames =>
`${packageManager} prettier --write ${filenames.join(' ')}`
}

export default options
13 changes: 11 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
"module": "src/index.ts",
"main": "src/index.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"prepare": "husky install",
"lint": "lint-staged",
"prettier": "prettier --write ."
},
"repository": {
"type": "git",
Expand All @@ -27,11 +30,17 @@
"middleware"
],
"dependencies": {
"@typescript-eslint/eslint-plugin": "^6.9.1",
"@typescript-eslint/parser": "^6.9.1",
"elysia": "^0.7.21",
"eslint": "^8.53.0",
"picocolors": "^1.0.0"
},
"devDependencies": {
"bun-types": "^1.0.8"
"bun-types": "^1.0.8",
"husky": "^8.0.3",
"lint-staged": "^15.0.2",
"prettier": "^3.0.3"
},
"peerDependencies": {
"typescript": "^5.0.0"
Expand Down
11 changes: 11 additions & 0 deletions prettier.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const options = {
arrowParens: 'avoid',
singleQuote: true,
bracketSpacing: true,
endOfLine: 'lf',
semi: false,
tabWidth: 2,
trailingComma: 'none'
}

module.exports = options
108 changes: 54 additions & 54 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,108 +1,108 @@
import Elysia from "elysia";
import * as pc from "picocolors";
import process from "process";
import Elysia from 'elysia'
import * as pc from 'picocolors'
import process from 'process'

export const logger = () =>
new Elysia({
name: "@grotto/logysia",
name: '@grotto/logysia'
})
.onRequest((ctx) => {
ctx.store = { ...ctx.store, beforeTime: process.hrtime.bigint() };
.onRequest(ctx => {
ctx.store = { ...ctx.store, beforeTime: process.hrtime.bigint() }
})
.onBeforeHandle((ctx) => {
ctx.store = { ...ctx.store, beforeTime: process.hrtime.bigint() };
.onBeforeHandle(ctx => {
ctx.store = { ...ctx.store, beforeTime: process.hrtime.bigint() }
})
.onAfterHandle(({ request, store }) => {
const logStr: string[] = [];
if (request.headers.get("X-Forwarded-For")) {
logStr.push(`[${pc.cyan(request.headers.get("X-Forwarded-For"))}]`);
const logStr: string[] = []
if (request.headers.get('X-Forwarded-For')) {
logStr.push(`[${pc.cyan(request.headers.get('X-Forwarded-For'))}]`)
}

logStr.push(methodString(request.method));
logStr.push(methodString(request.method))

logStr.push(new URL(request.url).pathname);
const beforeTime: bigint = (store as any).beforeTime;
logStr.push(new URL(request.url).pathname)
const beforeTime: bigint = (store as any).beforeTime

logStr.push(durationString(beforeTime));
logStr.push(durationString(beforeTime))

console.log(logStr.join(" "));
console.log(logStr.join(' '))
})
.onError(({ request, error, store }) => {
const logStr: string[] = [];
const logStr: string[] = []

logStr.push(pc.red(methodString(request.method)));
logStr.push(pc.red(methodString(request.method)))

logStr.push(new URL(request.url).pathname);
logStr.push(new URL(request.url).pathname)

logStr.push(pc.red("Error"));
logStr.push(pc.red('Error'))

if ("status" in error) {
logStr.push(String(error.status));
if ('status' in error) {
logStr.push(String(error.status))
}

logStr.push(error.message);
const beforeTime: bigint = (store as any).beforeTime;
logStr.push(error.message)
const beforeTime: bigint = (store as any).beforeTime

logStr.push(durationString(beforeTime));
logStr.push(durationString(beforeTime))

console.log(logStr.join(" "));
});
console.log(logStr.join(' '))
})

function durationString(beforeTime: bigint): string {
const now = process.hrtime.bigint();
const timeDifference = now - beforeTime;
const nanoseconds = Number(timeDifference);
const now = process.hrtime.bigint()
const timeDifference = now - beforeTime
const nanoseconds = Number(timeDifference)

const durationInMicroseconds = (nanoseconds / 1e3).toFixed(0); // Convert to microseconds
const durationInMilliseconds = (nanoseconds / 1e6).toFixed(0); // Convert to milliseconds
let timeMessage: string = "";
const durationInMicroseconds = (nanoseconds / 1e3).toFixed(0) // Convert to microseconds
const durationInMilliseconds = (nanoseconds / 1e6).toFixed(0) // Convert to milliseconds
let timeMessage: string = ''

if (nanoseconds >= 1e9) {
const seconds = (nanoseconds / 1e9).toFixed(2);
timeMessage = `| ${seconds}s`;
const seconds = (nanoseconds / 1e9).toFixed(2)
timeMessage = `| ${seconds}s`
} else if (nanoseconds >= 1e6) {
timeMessage = `| ${durationInMilliseconds}ms`;
timeMessage = `| ${durationInMilliseconds}ms`
} else if (nanoseconds >= 1e3) {
timeMessage = `| ${durationInMicroseconds}µs`;
timeMessage = `| ${durationInMicroseconds}µs`
} else {
timeMessage = `| ${nanoseconds}ns`;
timeMessage = `| ${nanoseconds}ns`
}

return timeMessage;
return timeMessage
}

function methodString(method: string): string {
switch (method) {
case "GET":
case 'GET':
// Handle GET request
return pc.white("GET");
return pc.white('GET')

case "POST":
case 'POST':
// Handle POST request
return pc.yellow("POST");
return pc.yellow('POST')

case "PUT":
case 'PUT':
// Handle PUT request
return pc.blue("PUT");
return pc.blue('PUT')

case "DELETE":
case 'DELETE':
// Handle DELETE request
return pc.red("DELETE");
return pc.red('DELETE')

case "PATCH":
case 'PATCH':
// Handle PATCH request
return pc.green("PATCH");
return pc.green('PATCH')

case "OPTIONS":
case 'OPTIONS':
// Handle OPTIONS request
return pc.gray("OPTIONS");
return pc.gray('OPTIONS')

case "HEAD":
case 'HEAD':
// Handle HEAD request
return pc.magenta("HEAD");
return pc.magenta('HEAD')

default:
// Handle unknown request method
return method;
return method
}
}
32 changes: 20 additions & 12 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"lib": ["ESNext"],
"module": "esnext",
"target": "esnext",
"moduleResolution": "bundler",
"moduleDetection": "force",
"allowImportingTsExtensions": true,
"noEmit": true,
"composite": true,
"noUncheckedIndexedAccess": true,
"strict": true,
"allowImportingTsExtensions": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"paths": {
"~/*": ["./src/*"]
},
"resolveJsonModule": true,
"types": ["bun-types"],
"downlevelIteration": true,
"skipLibCheck": true,
"jsx": "preserve",
"noEmit": true,
"allowJs": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
"types": ["bun-types"]
"jsx": "react",
"jsxFactory": "ElysiaJSX",
"jsxFragmentFactory": "ElysiaJSX.Fragment",
"lib": ["ESNext"],
"moduleDetection": "force",
"target": "ESNext",
"composite": true,
"skipLibCheck": true
}
}

0 comments on commit 6f5e553

Please sign in to comment.