Commit 6c68b8cf by hometown

feat: init project

parents
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
\ No newline at end of file
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
{
"recommendations": [
// my extensions, ofc :P
"antfu.browse-lite",
"antfu.iconify",
"antfu.slidev",
"antfu.unocss",
"antfu.vite",
"antfu.where-am-i",
"antfu.open-in-github-button",
"lokalise.i18n-ally",
// themes & icons
"antfu.icons-carbon",
"antfu.theme-vitesse",
"file-icons.file-icons",
"sainnhe.gruvbox-material",
// life savers!
"dbaeumer.vscode-eslint",
"Vue.volar",
"GitHub.copilot",
"usernamehw.errorlens",
"streetsidesoftware.code-spell-checker",
// up to you
"eamodio.gitlens",
"EditorConfig.EditorConfig",
"github.vscode-github-actions",
"GitHub.vscode-pull-request-github",
"johnsoncodehk.vscode-tsconfig-helper",
"mpontus.tab-cycle",
"naumovs.color-highlight",
"WakaTime.vscode-wakatime",
"znck.grammarly"
]
}
{
// Visuals
"workbench.colorTheme": "Vitesse Dark",
"workbench.editor.tabCloseButton": "left",
"workbench.fontAliasing": "antialiased",
"workbench.iconTheme": "file-icons",
"workbench.list.smoothScrolling": true,
"workbench.preferredDarkColorTheme": "Vitesse Dark",
"workbench.preferredLightColorTheme": "Vitesse Light",
"workbench.productIconTheme": "icons-carbon",
"workbench.sideBar.location": "right",
"workbench.startupEditor": "newUntitledFile",
"workbench.tree.expandMode": "singleClick",
"workbench.tree.indent": 10,
"editor.fontFamily": "Input Mono, Fira Code, monospace",
"editor.fontLigatures": "'ss01', 'ss02', 'ss03', 'ss06', 'zero'",
// Editor
"editor.accessibilitySupport": "off",
"editor.cursorSmoothCaretAnimation": "on",
"editor.find.addExtraSpaceOnTop": false,
"editor.guides.bracketPairs": "active",
"editor.inlineSuggest.enabled": true,
"editor.lineNumbers": "interval",
// "editor.multiCursorModifier": "ctrlCmd",
"editor.renderWhitespace": "boundary",
"editor.suggestSelection": "first",
"editor.tabSize": 2,
"editor.unicodeHighlight.invisibleCharacters": false,
"editor.stickyScroll.enabled": true,
"editor.hover.sticky": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit",
"source.organizeImports": "never"
},
"editor.wordSeparators": "`~!@#%^&*()=+[{]}\\|;:'\",.<>/?",
"explorer.confirmDelete": false,
"explorer.confirmDragAndDrop": false,
"window.autoDetectColorScheme": true,
"window.dialogStyle": "custom",
"window.nativeTabs": true, // this is great, macOS only
"window.titleBarStyle": "custom",
"workbench.editor.closeOnFileDelete": true,
"workbench.editor.highlightModifiedTabs": true,
"workbench.editor.limit.enabled": true,
"workbench.editor.limit.perEditorGroup": true,
"workbench.editor.limit.value": 5,
"extensions.autoUpdate": "onlyEnabledExtensions",
"extensions.ignoreRecommendations": true,
"files.eol": "\n",
"files.insertFinalNewline": true,
"files.simpleDialog.enable": true,
"git.autofetch": true,
"git.confirmSync": false,
"git.enableSmartCommit": true,
"git.untrackedChanges": "separate",
"terminal.integrated.cursorBlinking": true,
"terminal.integrated.cursorStyle": "line",
"terminal.integrated.fontWeight": "300",
"terminal.integrated.persistentSessionReviveProcess": "never",
"terminal.integrated.tabs.enabled": true,
"scm.diffDecorationsGutterWidth": 2,
"debug.onTaskErrors": "debugAnyway",
"diffEditor.ignoreTrimWhitespace": false,
"search.exclude": {
"**/.git": true,
"**/.github": true,
"**/.nuxt": true,
"**/.output": true,
"**/.pnpm": true,
"**/.vscode": true,
"**/.yarn": true,
"**/bower_components": true,
"**/dist/**": true,
"**/logs": true,
"**/node_modules": true,
"**/out/**": true,
"**/package-lock.json": true,
"**/pnpm-lock.yaml": true,
"**/tmp": true,
"**/yarn.lock": true
},
// Extension configs
"emmet.showSuggestionsAsSnippets": true,
"emmet.triggerExpansionOnTab": false,
"errorLens.enabledDiagnosticLevels": [
"warning",
"error"
],
"errorLens.excludeBySource": [
"cSpell",
"Grammarly",
"eslint"
],
// ESLint config: https://github.com/antfu/eslint-config
// Enable the ESlint flat config support
"eslint.experimental.useFlatConfig": true,
// Disable the default formatter, use eslint instead
"editor.formatOnSave": false,
// Silent the stylistic rules in you IDE, but still auto fix them
"eslint.rules.customizations": [
{ "rule": "style/*", "severity": "off" },
{ "rule": "format/*", "severity": "off" },
{ "rule": "*-indent", "severity": "off" },
{ "rule": "*-spacing", "severity": "off" },
{ "rule": "*-spaces", "severity": "off" },
{ "rule": "*-order", "severity": "off" },
{ "rule": "*-dangle", "severity": "off" },
{ "rule": "*-newline", "severity": "off" },
{ "rule": "*quotes", "severity": "off" },
{ "rule": "*semi", "severity": "off" }
],
// Enable eslint for all supported languages
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
"vue",
"html",
"markdown",
"json",
"jsonc",
"yaml",
"toml"
],
"github.copilot.enable": {
"*": true,
"markdown": true,
"plaintext": false,
"yaml": false
},
"cSpell.allowCompoundWords": true,
"cSpell.language": "en,en-US",
"css.lint.hexColorLength": "ignore",
"githubIssues.workingIssueFormatScm": "#${issueNumberLabel}",
"githubPullRequests.fileListLayout": "tree",
"gitlens.codeLens.authors.enabled": false,
"gitlens.codeLens.enabled": false,
"gitlens.codeLens.recentChange.enabled": false,
"gitlens.menus": {
"editor": {
"blame": false,
"clipboard": true,
"compare": true,
"history": false,
"remote": false
},
"editorGroup": {
"blame": true,
"compare": false
},
"editorTab": {
"clipboard": true,
"compare": true,
"history": true,
"remote": true
},
"explorer": {
"clipboard": true,
"compare": true,
"history": true,
"remote": true
},
"scm": {
"authors": true
},
"scmGroup": {
"compare": true,
"openClose": true,
"stash": true
},
"scmGroupInline": {
"stash": true
},
"scmItem": {
"clipboard": true,
"compare": true,
"history": true,
"remote": false,
"stash": true
}
},
"i18n-ally.autoDetection": false,
"i18n-ally.displayLanguage": "en",
"i18n-ally.ignoredLocales": [],
"iconify.annotations": true,
"iconify.inplace": true,
"svg.preview.mode": "svg",
// I only use Prettier for manually formatting
"prettier.enable": false,
"prettier.printWidth": 200,
"prettier.semi": false,
"prettier.singleQuote": true,
// File Nesting
// this might not be up to date with the repo, please check yourself
// https://github.com/antfu/vscode-file-nesting-config
"explorer.fileNesting.enabled": true,
"explorer.fileNesting.expand": false,
"explorer.fileNesting.patterns": {
"*.asax": "$(capture).*.cs, $(capture).*.vb",
"*.ascx": "$(capture).*.cs, $(capture).*.vb",
"*.ashx": "$(capture).*.cs, $(capture).*.vb",
"*.aspx": "$(capture).*.cs, $(capture).*.vb",
"*.bloc.dart": "$(capture).event.dart, $(capture).state.dart",
"*.c": "$(capture).h",
"*.cc": "$(capture).hpp, $(capture).h, $(capture).hxx",
"*.cjs": "$(capture).cjs.map, $(capture).*.cjs, $(capture)_*.cjs",
"*.component.ts": "$(capture).component.html, $(capture).component.spec.ts, $(capture).component.css, $(capture).component.scss, $(capture).component.sass, $(capture).component.less",
"*.cpp": "$(capture).hpp, $(capture).h, $(capture).hxx",
"*.cs": "$(capture).*.cs",
"*.cshtml": "$(capture).cshtml.cs",
"*.csproj": "*.config, *proj.user, appsettings.*, bundleconfig.json",
"*.css": "$(capture).css.map, $(capture).*.css",
"*.cxx": "$(capture).hpp, $(capture).h, $(capture).hxx",
"*.dart": "$(capture).freezed.dart, $(capture).g.dart",
"*.ex": "$(capture).html.eex, $(capture).html.heex, $(capture).html.leex",
"*.go": "$(capture)_test.go",
"*.java": "$(capture).class",
"*.js": "$(capture).js.map, $(capture).*.js, $(capture)_*.js",
"*.jsx": "$(capture).js, $(capture).*.jsx, $(capture)_*.js, $(capture)_*.jsx",
"*.master": "$(capture).*.cs, $(capture).*.vb",
"*.mjs": "$(capture).mjs.map, $(capture).*.mjs, $(capture)_*.mjs",
"*.module.ts": "$(capture).resolver.ts, $(capture).controller.ts, $(capture).service.ts",
"*.pubxml": "$(capture).pubxml.user",
"*.resx": "$(capture).*.resx, $(capture).designer.cs, $(capture).designer.vb",
"*.tex": "$(capture).acn, $(capture).acr, $(capture).alg, $(capture).aux, $(capture).bbl, $(capture).blg, $(capture).fdb_latexmk, $(capture).fls, $(capture).glg, $(capture).glo, $(capture).gls, $(capture).idx, $(capture).ind, $(capture).ist, $(capture).lof, $(capture).log, $(capture).lot, $(capture).out, $(capture).pdf, $(capture).synctex.gz, $(capture).toc, $(capture).xdv",
"*.ts": "$(capture).js, $(capture).d.ts.map, $(capture).*.ts, $(capture)_*.js, $(capture)_*.ts",
"*.tsx": "$(capture).ts, $(capture).*.tsx, $(capture)_*.ts, $(capture)_*.tsx",
"*.vbproj": "*.config, *proj.user, appsettings.*, bundleconfig.json",
"*.vue": "$(capture).*.ts, $(capture).*.js, $(capture).story.vue",
"*.xaml": "$(capture).xaml.cs",
"+layout.svelte": "+layout.ts,+layout.ts,+layout.js,+layout.server.ts,+layout.server.js,+layout.gql",
"+page.svelte": "+page.server.ts,+page.server.js,+page.ts,+page.js,+page.gql",
".clang-tidy": ".clang-format, .clangd, compile_commands.json",
".env": "*.env, .env.*, .envrc, env.d.ts",
".gitignore": ".gitattributes, .gitmodules, .gitmessage, .mailmap, .git-blame*",
".project": ".classpath",
"//": "Last update at 4/29/2023, 2:04:58 PM",
"BUILD.bazel": "*.bzl, *.bazel, *.bazelrc, bazel.rc, .bazelignore, .bazelproject, WORKSPACE",
"CMakeLists.txt": "*.cmake, *.cmake.in, .cmake-format.yaml, CMakePresets.json",
"I*.cs": "$(capture).cs",
"artisan": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .envrc, .htmlnanorc*, .lighthouserc.*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, contentlayer.config.*, cssnano.config.*, cypress.*, env.d.ts, formkit.config.*, formulate.config.*, histoire.config.*, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, lighthouserc.*, playwright.config.*, postcss.config.*, puppeteer.config.*, rspack.config.*, server.php, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, uno.config.*, unocss.config.*, vitest.config.*, webpack.config.*, webpack.mix.js, windi.config.*",
"astro.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .envrc, .htmlnanorc*, .lighthouserc.*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, contentlayer.config.*, cssnano.config.*, cypress.*, env.d.ts, formkit.config.*, formulate.config.*, histoire.config.*, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, lighthouserc.*, playwright.config.*, postcss.config.*, puppeteer.config.*, rspack.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, uno.config.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"cargo.toml": ".clippy.toml, .rustfmt.toml, cargo.lock, clippy.toml, cross.toml, rust-toolchain.toml, rustfmt.toml",
"composer.json": ".php*.cache, composer.lock, phpunit.xml*, psalm*.xml",
"default.nix": "shell.nix",
"deno.json*": "*.env, .env.*, .envrc, api-extractor.json, deno.lock, env.d.ts, import-map.json, import_map.json, jsconfig.*, tsconfig.*, tsdoc.*",
"dockerfile": ".dockerignore, docker-compose.*, dockerfile*",
"flake.nix": "flake.lock",
"gatsby-config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .envrc, .htmlnanorc*, .lighthouserc.*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, contentlayer.config.*, cssnano.config.*, cypress.*, env.d.ts, formkit.config.*, formulate.config.*, gatsby-browser.*, gatsby-node.*, gatsby-ssr.*, gatsby-transformer.*, histoire.config.*, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, lighthouserc.*, playwright.config.*, postcss.config.*, puppeteer.config.*, rspack.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, uno.config.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"gemfile": ".ruby-version, gemfile.lock",
"go.mod": ".air*, go.sum",
"go.work": "go.work.sum",
"mix.exs": ".credo.exs, .dialyzer_ignore.exs, .formatter.exs, .iex.exs, .tool-versions, mix.lock",
"next.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .envrc, .htmlnanorc*, .lighthouserc.*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, contentlayer.config.*, cssnano.config.*, cypress.*, env.d.ts, formkit.config.*, formulate.config.*, histoire.config.*, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, lighthouserc.*, next-env.d.ts, playwright.config.*, postcss.config.*, puppeteer.config.*, rspack.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, uno.config.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"nuxt.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .envrc, .htmlnanorc*, .lighthouserc.*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, contentlayer.config.*, cssnano.config.*, cypress.*, env.d.ts, formkit.config.*, formulate.config.*, histoire.config.*, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, lighthouserc.*, playwright.config.*, postcss.config.*, puppeteer.config.*, rspack.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, uno.config.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"package.json": ".browserslist*, .circleci*, .commitlint*, .cz-config.js, .czrc, .dlint.json, .dprint.json, .editorconfig, .eslint*, .firebase*, .flowconfig, .github*, .gitlab*, .gitpod*, .huskyrc*, .jslint*, .lintstagedrc*, .markdownlint*, .node-version, .nodemon*, .npm*, .nvmrc, .pm2*, .pnp.*, .pnpm*, .prettier*, .releaserc*, .sentry*, .simple-git-hooks*, .stackblitz*, .styleci*, .stylelint*, .tazerc*, .textlint*, .tool-versions, .travis*, .versionrc*, .vscode*, .watchman*, .xo-config*, .yamllint*, .yarnrc*, Procfile, apollo.config.*, appveyor*, azure-pipelines*, bower.json, build.config.*, commitlint*, crowdin*, dangerfile*, dlint.json, dprint.json, eslint*, firebase.json, grunt*, gulp*, jenkins*, lerna*, lint-staged*, nest-cli.*, netlify*, nodemon*, npm-shrinkwrap.json, nx.*, package-lock.json, package.nls*.json, phpcs.xml, pm2.*, pnpm*, prettier*, pullapprove*, pyrightconfig.json, release-tasks.sh, release.config.*, renovate*, rollup.config.*, rspack*, simple-git-hooks*, stylelint*, tslint*, tsup.config.*, turbo*, typedoc*, unlighthouse*, vercel*, vetur.config.*, webpack*, workspace.json, xo.config.*, yarn*",
"pubspec.yaml": ".metadata, .packages, all_lint_rules.yaml, analysis_options.yaml, build.yaml, pubspec.lock, pubspec_overrides.yaml",
"pyproject.toml": ".pdm.toml, pdm.lock, pyproject.toml",
"quasar.conf.js": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .envrc, .htmlnanorc*, .lighthouserc.*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, contentlayer.config.*, cssnano.config.*, cypress.*, env.d.ts, formkit.config.*, formulate.config.*, histoire.config.*, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, lighthouserc.*, playwright.config.*, postcss.config.*, puppeteer.config.*, quasar.extensions.json, rspack.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, uno.config.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"readme*": "authors, backers*, changelog*, citation*, code_of_conduct*, codeowners, contributing*, contributors, copying, credits, governance.md, history.md, license*, maintainers, readme*, security.md, sponsors*",
"remix.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .envrc, .htmlnanorc*, .lighthouserc.*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, contentlayer.config.*, cssnano.config.*, cypress.*, env.d.ts, formkit.config.*, formulate.config.*, histoire.config.*, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, lighthouserc.*, playwright.config.*, postcss.config.*, puppeteer.config.*, remix.*, rspack.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, uno.config.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"rush.json": ".browserslist*, .circleci*, .commitlint*, .cz-config.js, .czrc, .dlint.json, .dprint.json, .editorconfig, .eslint*, .firebase*, .flowconfig, .github*, .gitlab*, .gitpod*, .huskyrc*, .jslint*, .lintstagedrc*, .markdownlint*, .node-version, .nodemon*, .npm*, .nvmrc, .pm2*, .pnp.*, .pnpm*, .prettier*, .releaserc*, .sentry*, .simple-git-hooks*, .stackblitz*, .styleci*, .stylelint*, .tazerc*, .textlint*, .tool-versions, .travis*, .versionrc*, .vscode*, .watchman*, .xo-config*, .yamllint*, .yarnrc*, Procfile, apollo.config.*, appveyor*, azure-pipelines*, bower.json, build.config.*, commitlint*, crowdin*, dangerfile*, dlint.json, dprint.json, eslint*, firebase.json, grunt*, gulp*, jenkins*, lerna*, lint-staged*, nest-cli.*, netlify*, nodemon*, npm-shrinkwrap.json, nx.*, package-lock.json, package.nls*.json, phpcs.xml, pm2.*, pnpm*, prettier*, pullapprove*, pyrightconfig.json, release-tasks.sh, release.config.*, renovate*, rollup.config.*, rspack*, simple-git-hooks*, stylelint*, tslint*, tsup.config.*, turbo*, typedoc*, unlighthouse*, vercel*, vetur.config.*, webpack*, workspace.json, xo.config.*, yarn*",
"shims.d.ts": "*.d.ts",
"svelte.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .envrc, .htmlnanorc*, .lighthouserc.*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, contentlayer.config.*, cssnano.config.*, cypress.*, env.d.ts, formkit.config.*, formulate.config.*, histoire.config.*, houdini.config.*, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, lighthouserc.*, mdsvex.config.js, playwright.config.*, postcss.config.*, puppeteer.config.*, rspack.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, uno.config.*, unocss.config.*, vite.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"vite.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .envrc, .htmlnanorc*, .lighthouserc.*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, contentlayer.config.*, cssnano.config.*, cypress.*, env.d.ts, formkit.config.*, formulate.config.*, histoire.config.*, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, lighthouserc.*, playwright.config.*, postcss.config.*, puppeteer.config.*, rspack.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, uno.config.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"vue.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .envrc, .htmlnanorc*, .lighthouserc.*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, contentlayer.config.*, cssnano.config.*, cypress.*, env.d.ts, formkit.config.*, formulate.config.*, histoire.config.*, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, lighthouserc.*, playwright.config.*, postcss.config.*, puppeteer.config.*, rspack.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, uno.config.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*"
},
"workbench.editor.tabActionLocation": "left"
}
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Installation
```bash
$ pnpm install
```
## Running the app
```bash
# development
$ pnpm run start
# watch mode
$ pnpm run start:dev
# production mode
$ pnpm run start:prod
```
## Test
```bash
# unit tests
$ pnpm run test
# e2e tests
$ pnpm run test:e2e
# test coverage
$ pnpm run test:cov
```
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}
{
"name": "service-nest",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^7.5.5",
"@nestjs/core": "^7.5.5",
"@nestjs/graphql": "^7.9.1",
"@nestjs/jwt": "^7.2.0",
"@nestjs/passport": "^7.1.5",
"@nestjs/platform-express": "^7.5.5",
"@nestjs/swagger": "^4.7.5",
"@nestjs/typeorm": "^7.1.5",
"apollo-server-express": "^2.19.0",
"bcrypt": "^5.0.0",
"body-parser-xml": "^2.0.1",
"class-transformer": "^0.3.1",
"class-validator": "^0.12.2",
"dayjs": "^1.9.7",
"express-rate-limit": "^5.2.3",
"graphql": "^15.4.0",
"graphql-tools": "^7.0.2",
"helmet": "^4.2.0",
"mysql": "^2.18.1",
"nestjs-config": "^1.4.7",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"reflect-metadata": "^0.1.13",
"request-ip": "^2.1.3",
"rimraf": "^3.0.2",
"rxjs": "^6.6.3",
"swagger-ui-express": "^4.1.5",
"typeorm": "^0.2.29"
},
"devDependencies": {
"@nestjs/cli": "^7.5.3",
"@nestjs/schematics": "^7.2.5",
"@nestjs/testing": "^7.5.5",
"@types/express": "^4.17.9",
"@types/jest": "26.0.18",
"@types/node": "^14.14.12",
"@types/passport-jwt": "^3.0.3",
"@types/passport-local": "^1.0.33",
"@types/supertest": "^2.0.10",
"@typescript-eslint/eslint-plugin": "^4.9.1",
"@typescript-eslint/parser": "^4.9.1",
"eslint": "^7.15.0",
"eslint-config-prettier": "^7.0.0",
"eslint-plugin-import": "^2.22.1",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"supertest": "^6.0.1",
"ts-jest": "26.4.4",
"ts-loader": "^8.0.11",
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.1.2"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ChatController } from './modules/chat/chat.controller';
import { ChatService } from './modules/chat/chat.service';
import { ChatModule } from './modules/chat/chat.module';
@Module({
imports: [ChatModule],
controllers: [AppController, ChatController],
providers: [AppService, ChatService],
})
export class AppModule {}
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
Logger,
HttpStatus,
} from '@nestjs/common';
import { GqlArgumentsHost } from '@nestjs/graphql';
import * as dayjs from 'dayjs';
// 需要实现 ExceptionFilter 接口,里面有一个catch方法需要实现
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp(); //获取状态信息
const response = ctx.getResponse();
const request = ctx.getRequest()
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const exceptionRes = exception.getResponse() as { error: string, message: string }
if (response?.status) {
const { error, message } = exceptionRes
const errorResponse = {
timestamp: dayjs().format('YYYY-MM-DD HH:mm:ss'),
message: message || exceptionRes,
path: request?.url,
status,
error,
code: 0,
ok: false,
result: {}
}
Logger.error(
`[${dayjs().format('YYYY-MM-DD HH:mm:ss')}] ${request?.method} ${request?.url}`,
JSON.stringify(errorResponse),
'HttpExceptionFilter',
);
response.status(status).json(errorResponse);
} else {
// 单独处理过滤graqhql的异常
const gqlHost = GqlArgumentsHost.create(host);
const httpRequest = this.getRequestFromCtx(ctx)
exception.message = `${exceptionRes.message || ''} ${exceptionRes.error || ''}`
// 异常错误
let request: any = {
graphql: {
args: gqlHost.getArgs(),
root: gqlHost.getRoot(),
},
}
try {
if (httpRequest) {
request = Object.assign(request, {
url: httpRequest.url,
body: httpRequest.body,
query: httpRequest.query,
params: httpRequest.params,
headers: httpRequest.headers,
currentUser: httpRequest.currentUser
})
}
request = JSON.stringify(request)
Logger.error(
`[${dayjs().format('YYYY-MM-DD HH:mm:ss')}] ${exception.message}`,
JSON.stringify(request),
'GraphQLExceptionFilter'
)
} catch {
Logger.error(
`[${dayjs().format('YYYY-MM-DD HH:mm:ss')}] ${exception.message}`,
'处理graqhql异常时',
'GraphQLExceptionFilter'
)
}
return exception;
}
}
getRequestFromCtx(ctx) {
for (let arg of ctx.args) {
if (arg && arg.request && arg.request?.url) {
return arg.request
}
}
}
}
import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response } from 'express';
import * as dayjs from "dayjs";
import { isEmpty } from 'class-validator';
@Injectable() // 使用Injectable装饰器
export class LoggerMiddleware implements NestMiddleware { // 使用NestMiddleware实现
use(req: Request, res: Response, next: Function) { // 重写方法
const { method, path, baseUrl } = req;
Logger.log(`[${dayjs().format('YYYY-MM-DD HH:mm:ss')}] ${method} ${baseUrl}`, 'LoggerMiddleware')
// 必须调用next()将控制权传递给下一个中间件功能。否则请求将被挂起
next();
}
}
// 全局监听
export function LoggerGlobal(req: Request, res: Response, next: Function) {
const { method, path } = req;
Logger.log(`[${dayjs().format('YYYY-MM-DD HH:mm:ss')}] ${method} ${path}`, 'LoggerGlobal');
next();
};
import { ArgumentMetadata, HttpException, HttpStatus, Injectable, PipeTransform, Type, } from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, metadata: ArgumentMetadata) {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) return value;
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
// const errObj = {};
// errors.forEach(err => {
// const {
// property,
// constraints,
// } = err;
// errObj[property] = Object.values(constraints);
// });
const errObj = Object.values(errors[0].constraints)[0];
throw new HttpException(
{ message: '请求参数验证失败 ', error: errObj },
HttpStatus.BAD_REQUEST,
);
}
return value;
}
private toValidate(metatype: Type<any>): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find(type => metatype === type);
}
}
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { classToPlain } from 'class-transformer';
import systemConfig from "../config/system";
const transformValue = (result: any, code: number = 0, message: string = '请求成功', ok = true) => {
const { returnFormat } = systemConfig
return {
[returnFormat.result]: classToPlain(result),
[returnFormat.code]: code,
[returnFormat.message]: message,
[returnFormat.ok]: ok,
}
}
// 处理统一成功返回值
@Injectable()
export class TransformReturnInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const host = context.switchToHttp();
const request = host.getRequest();
// 不需要格式化的接口
if (['/api/status'].includes(request?.url)) {
return next.handle();
}
return next.handle().pipe(map(transformValue))
}
}
const system = {
adminPath: 'admin', // 管理员路径
staticPrefixPath: '', // 静态文件的前缀
supportImgTypes: ['.png', '.jpg', '.gif', '.jpeg'], //支持的图片
defaultAccount: 'admin', // 默认账号
defaultPassword: '123456', // 默认密码
returnFormat: {
result: 'result',
code: 'code',
message: 'message',
ok: 'ok'
}
}
export default system
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger } from '@nestjs/common';
import { LoggerGlobal } from './common/logger.middleware';
import { ValidationPipe } from './common/pipes/validation.pipe';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import * as rateLimit from 'express-rate-limit';
import * as requestIp from 'request-ip';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { TransformReturnInterceptor } from './common/transform.return';
const bodyParser = require('body-parser');
require('body-parser-xml')(bodyParser);
const PORT = 3333;
const PREFIX = 'api'
const SWAGGER_V1 = `${PREFIX}/v1/swagger`
async function bootstrap() {
const app = await NestFactory.create(AppModule)
app.setGlobalPrefix(PREFIX);
const options = new DocumentBuilder() // 创建并配置文档信息
.setTitle('标题')
.setDescription('描述信息')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, options);
// 会自动将所有路由显示出来
SwaggerModule.setup(SWAGGER_V1, app, document); // api/swagger = API文档的路径,访问:http://localhost:3000/api/swagger
// 跨域资源共享
app.enableCors()
// 限制访问频率
app.use(
rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 500, // 限制15分钟内最多只能访问500次
}),
);
app.use(bodyParser.xml({
limit: '1MB', // 拒绝大于1 MB的有效负载
xmlParseOptions: {
normalize: true, // 在文本节点内修剪空格
normalizeTags: true, // 将标签转换为小写
explicitArray: false // 如果> 1,则仅将节点放入数组
}
}));
// 拦截处理-错误异常
// graphQL专属异常过滤
// app.useGlobalFilters(new GraphQLExceptionFilter());
app.useGlobalFilters(new HttpExceptionFilter());
// 拦截处理-返回格式
app.useGlobalInterceptors(new TransformReturnInterceptor());
// 获取访问者ip地址
app.use(requestIp.mw());
// 全局监听路由请求
app.use(LoggerGlobal);
// 使用管道验证数据
app.useGlobalPipes(new ValidationPipe());
await app.listen(PORT, () => {
Logger.log(`已启动,接口: http://localhost:${PORT}/${PREFIX} , API文档:http://localhost:${PORT}/${SWAGGER_V1}`);
});
}
bootstrap().catch(err => Logger.error('启动错误:', err));
import { Test, TestingModule } from '@nestjs/testing';
import { ChatController } from './chat.controller';
describe('ChatController', () => {
let controller: ChatController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ChatController],
}).compile();
controller = module.get<ChatController>(ChatController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
import { ChatService } from './chat.service';
import { Body, Controller, HttpException, HttpStatus, Post, Req } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { sendMessageDto } from './dto/sendMessage.dto';
@ApiTags('chat')
@Controller('chat')
export class ChatController {
constructor(private readonly chatService: ChatService) {}
@ApiOperation({ summary: '发送消息', description: '向ERNIE Bot模型发送消息得到答案' })
@Post('sendMessage')
sendMessage(@Body() body: sendMessageDto) {
try {
return this.chatService.sendMessage(body.messages)
} catch (error) {
new HttpException({ message: '服务端错误 ', error: error }, HttpStatus.BAD_REQUEST)
}
}
}
import { Module } from '@nestjs/common';
import { ChatController } from './chat.controller';
import { ChatService } from './chat.service';;
@Module({
controllers: [ChatController],
providers: [ChatService],
})
export class ChatModule { }
import { Test, TestingModule } from '@nestjs/testing';
import { ChatService } from './chat.service';
describe('ChatService', () => {
let service: ChatService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ChatService],
}).compile();
service = module.get<ChatService>(ChatService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
import { Injectable } from '@nestjs/common';
import type { Message } from './dto/sendMessage.dto';
@Injectable()
export class ChatService {
sendMessage(messages: Message[]) {
return messages
}
}
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsArray, ArrayMinSize } from "class-validator"
export interface Message {
role: 'user' | 'admin'
content: string
}
export class sendMessageDto {
@IsArray({message: '消息数组必须是数组'})
@ArrayMinSize(1, {message: '消息数组长度最小为1'})
@ApiPropertyOptional({ description: '消息数组', example: [{ role: 'user', content: '你好' }] })
public readonly messages: Message[]
}
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment