Skip to content
Snippets Groups Projects
Commit f8b49603 authored by Emmanuel Salomon's avatar Emmanuel Salomon :fist:
Browse files

First commit with polkadot

parents
No related branches found
No related tags found
No related merge requests found
PORT=3000 # Only for production, port for dev is 3000. See vite.config.ts
\ No newline at end of file
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ main ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ main ]
schedule:
- cron: '27 19 * * 3'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'javascript' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://git.io/codeql-language-support
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
# fastify
# build
/build/
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
.env.production
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
\ No newline at end of file
.nvmrc 0 → 100644
v14.17.1
# Ignore artifacts:
build
coverage
\ No newline at end of file
{
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"useTabs": false,
"trailingComma": "none"
}
This diff is collapsed.
README.md 0 → 100644
<p align="center">
<img src="https://repository-images.githubusercontent.com/446977257/2937768f-1569-45a6-ac60-a7b44a78225b" alt="vite-fastify-boilerplate"/>
</p>
[![GitHub license](https://img.shields.io/github/license/ManUtopiK/vite-fastify-boilerplate)](https://github.com/ManUtopiK/vite-fastify-boilerplate/blob/main/LICENCE)
[![GitHub issues](https://img.shields.io/github/issues/ManUtopiK/vite-fastify-boilerplate)](https://github.com/ManUtopiK/vite-fastify-boilerplate/issues)
[![Coverage Status](https://img.shields.io/badge/coverage-100-green.svg)](https://coveralls.io/github/ManUtopiK/vite-fastify-boilerplate?branch=main)
[![Sync Vulnerabilities Status](https://app.snyk.io/test/github/ManUtopiK/vite-fastify-boilerplate/badge.svg)](https://snyk.io/test/github/ManUtopiK/vite-fastify-boilerplate)
[![Twitter](https://img.shields.io/twitter/url?url=https%3A%2F%2Fgithub.com%2FManUtopiK%2Fvite-fastify-boilerplate)](https://twitter.com/intent/tweet?text=Wow%21%20%23Fastify%20with%20%23Vitejs%20and%20%23Vitest%20%F0%9F%9A%80&url=httpsgithub.com%2FManUtopiK%2Fvite-fastify-boilerplate)
Enhance your [Fastify](https://github.com/fastify/fastify) DX with the power of [Vite](https://vitejs.dev) & [Vitest](https://vitest.dev/).
## Features
- ⚡ All the power of Vite (Next Generation ~~Frontend~~ Isomorphic Tooling):
- Lightning fast HMR (hot module replacement) in dev mode with [Vite Plugin Node](https://github.com/axe-me/vite-plugin-node#readme).
- Smart & instant watch mode, like HMR for tests with [Vitest](https://vitest.dev/).
- 🛠️ DX setup:
- Vite, Prettier and Typescript with common config, esnext ready and alias `@/*`
- Tests with one Fastify instance setup, code coverage
- Fastify with logger
- Production build without Vite
So, it's super fast donc ça va super vite 🚀
## Why and How
See [Why and How Vite in node](https://github.com/axe-me/vite-plugin-node#why) and [Why Vitest](https://vitest.dev/guide/why.html).
## Get started
1. Clone this repo or use [tiged](https://github.com/tiged/tiged) with:
```bash
degit https://github.com/ManUtopiK/vite-fastify-boilerplate
```
2. Install:
```bash
pnpm install
```
**Start dev mode using Vite:**
```bash
pnpm dev
```
**Start test mode using Vitest:**
```bash
pnpm test
```
**Start test mode with coverage:**
```bash
pnpm coverage
```
**Compile typescript to javascript:**
```bash
pnpm build
```
**Start for production:**
```bash
pnpm start
```
## Code
- Main file: `src/app.ts`
- Configure logger: `src/logger.ts`
- Change port in `.env`
### Docs
- [Vite](https://vitejs.dev/)
- [Vite Plugin Node](https://github.com/axe-me/vite-plugin-node)
- [Vitest](https://vitest.dev/)
- [Fastify](https://www.fastify.io/docs/latest/)
### Ressources
- [Awesome vite](https://github.com/vitejs/awesome-vite)
- [Fastify ecosystem](https://www.fastify.io/ecosystem/)
### Add vite plugin example
#### Import `.gql` and `.graphql` files
1. **Install packages:**
```bash
pnpm add graphql graphql-tag
pnpm add -D vite-plugin-simple-gql
```
2. **Configure `vite.config.ts`:**
```js
import gql from 'vite-plugin-simple-gql'
```
And add `gql()` to `plugins`:
```js
plugins: [gql(), ...]
```
Now you can import your graphql files in your code:
```js
// example.ts
import MyQuery from './MyQuery.gql'
```
## Contributions
If you would like to make any contribution you are welcome to do so.
## Known issues
- Websockets don't work with vite-plugin-node. [See here](https://github.com/axe-me/vite-plugin-node/issues/22). To develop with websockets, you should start Fastify as usual.
- Vitest UI doesn't work.
Please create an issue if you found any bugs, to help me improve this project!
{
"name": "vite-fastify-boilerplate",
"version": "0.0.2",
"description": "Fastify boilerplate with Vite & Vitest",
"main": "build/server.js",
"scripts": {
"dev": "vite",
"build": "vite build --outDir build --ssr src/server.ts",
"start": "yarn build && node build/server.js",
"test": "vitest",
"coverage": "vitest --coverage"
},
"keywords": [
"fastify",
"vite",
"vitest",
"boilerplate",
"typescript",
"HMR"
],
"author": "Emmanuel Salomon <emmanuel.salomon@gmail.com> (https://github.com/ManUtopiK)",
"license": "GPL-3.0-or-later",
"dependencies": {
"@polkadot/api": "^8.5.1",
"@swc/core": "^1.2.194",
"env-schema": "^4.0.0",
"fastify": "^3.27.4",
"pino": "^7.9.2",
"pino-pretty": "^7.5.4"
},
"devDependencies": {
"@types/node": "^17.0.22",
"@vitest/ui": "^0.7.7",
"c8": "^7.11.0",
"vite": "^2.8.6",
"vite-plugin-node": "^0.0.18",
"vitest": "^0.7.7"
}
}
\ No newline at end of file
This diff is collapsed.
import { describe, it, expect } from 'vitest'
import fastify from '@/test'
describe('Test server health', () => {
it('serve GET /', async () => {
const res = await fastify.inject('/')
expect(res.json()).toEqual({ hello: 'world' })
})
})
import { fastify as Fastify, FastifyServerOptions } from 'fastify'
// Import
import { ApiPromise, WsProvider } from '@polkadot/api';
export default (opts?: FastifyServerOptions) => {
const fastify = Fastify(opts)
/* Your code here. Hello world example: */
fastify.get('/', async (request, reply) => {
// Construct
const wsProvider = new WsProvider('wss://gdev.librelois.fr/ws');
const api = await ApiPromise.create({ provider: wsProvider });
// Do something
return {
genesis: api.genesisHash.toHex(),
chain: await api.rpc.chain.getHeader(),
}
})
return fastify
}
import fs from 'fs'
// Create dir for logs
const logDir = './logs'
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir, { recursive: true })
}
// Set logger options
const logger = import.meta.env.DEV
? {
prettyPrint: {
translateTime: 'HH:MM:ss.l',
ignore: 'pid,hostname'
}
}
: {
level: 'warn',
file: logDir + '/warn-logs.log'
}
export default logger
import envSchema from 'env-schema'
import fastify from './app'
import logger from './logger'
const app = fastify({
logger,
pluginTimeout: 50000,
bodyLimit: 15485760
})
if (import.meta.env.PROD) {
try {
// Get port from .env or 3000
const { PORT } = envSchema({
dotenv: true,
schema: {
type: 'object',
required: ['PORT'],
properties: {
PORT: {
type: 'string',
default: 3000
}
}
}
})
app.listen(PORT as string, '0.0.0.0')
console.log(`Server started on 0.0.0.0:${PORT}`)
} catch (err) {
app.log.error(err)
process.exit(1)
}
}
export const viteNodeApp = app
import { beforeAll, afterAll } from 'vitest'
import buildFastify from './app'
const fastify = buildFastify()
beforeAll(async () => {
// called once before all tests run
await fastify.ready()
})
afterAll(async () => {
// called once after all tests run
await fastify.close()
})
export default fastify
/// <reference types="vite/client" />
{
"compilerOptions": {
"moduleResolution": "node",
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"target": "esnext",
"module": "esnext",
"types": [
"vite/client"
],
"paths": {
"@/*": [
"./src/*"
]
}
}
}
\ No newline at end of file
/// <reference types="vitest" />
import { defineConfig } from 'vite'
import { VitePluginNode } from 'vite-plugin-node'
import * as path from 'path'
export default defineConfig({
server: {
// vite server configs, for details see [vite doc](https://vitejs.dev/config/#server-host)
port: 3000
},
plugins: [
...VitePluginNode({
// Nodejs native Request adapter
// currently this plugin support 'express', 'nest', 'koa' and 'fastify' out of box,
// you can also pass a function if you are using other frameworks, see Custom Adapter section
adapter: 'fastify',
// tell the plugin where is your project entry
appPath: './src/server.ts',
// Optional, default: 'viteNodeApp'
// the name of named export of you app from the appPath file
exportName: 'viteNodeApp',
// Optional, default: 'esbuild'
// The TypeScript compiler you want to use
// by default this plugin is using vite default ts compiler which is esbuild
// 'swc' compiler is supported to use as well for frameworks
// like Nestjs (esbuild dont support 'emitDecoratorMetadata' yet)
tsCompiler: 'esbuild'
})
],
test: {},
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
}
})
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment