Skip to content

Commit

Permalink
start repo
Browse files Browse the repository at this point in the history
  • Loading branch information
pedrouid committed Jun 3, 2019
0 parents commit 1dfd150
Show file tree
Hide file tree
Showing 15 changed files with 4,173 additions and 0 deletions.
11 changes: 11 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "usage"
}
],
"@babel/typescript"
]
}
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build
3 changes: 3 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "standard"
}
47 changes: 47 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Logs
logs
*.log
npm-debug.log*

# 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

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Dependency directories
node_modules
jspm_packages

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

dist
build

.DS_Store
.env
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Pedro Gomes

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# fastify-ts-boilerplate

Boilerplate Server built with Fastify and Typescript
3 changes: 3 additions & 0 deletions babel-polyfill.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
require('@babel/register')({
extensions: ['.ts', '.js', '.tsx', '.jsx']
})
56 changes: 56 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"name": "fastify-ts-boilerplate",
"description": "Boilerplate Server built with Fastify and Typescript",
"version": "0.1.0",
"private": true,
"main": "src/index.ts",
"keywords": [
"fastify",
"server",
"typescript",
"boilerplate",
"api"
],
"author": "Pedro Gomes <pedro@pedrouid.com>",
"license": "MIT",
"scripts": {
"dev": "babel-node --extensions '.ts' src/index.ts",
"build": "babel ./src --extensions '.ts' --out-dir ./build",
"test": "mocha --require ./babel-polyfill.js test/**/*.spec.ts",
"start": "node ./build",
"deploy": "NODE_ENV=production pm2 start ./build --name=server"
},
"dependencies": {
"axios": "^0.18.0",
"dotenv": "^7.0.0",
"fastify": "^1.14.1",
"fastify-cors": "^1.0.0",
"fastify-helmet": "^3.0.0"
},
"devDependencies": {
"@babel/cli": "^7.1.2",
"@babel/core": "^7.1.2",
"@babel/node": "^7.0.0",
"@babel/polyfill": "^7.0.0",
"@babel/preset-env": "^7.1.0",
"@babel/preset-typescript": "^7.1.0",
"@babel/register": "^7.0.0",
"@types/chai": "^4.1.6",
"@types/dotenv": "^6.1.0",
"@types/fastify-cors": "^0.1.0",
"@types/mocha": "^5.2.5",
"@types/node": "^10.12.0",
"chai": "^4.2.0",
"eslint": "^5.8.0",
"eslint-config-standard": "^12.0.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-node": "^7.0.1",
"eslint-plugin-promise": "^4.0.1",
"eslint-plugin-standard": "^4.0.0",
"isomorphic-fetch": "^2.2.1",
"mocha": "^5.2.0",
"tslint": "^5.11.0",
"tslint-config-standard": "^8.0.1",
"typescript": "^3.1.3"
}
}
16 changes: 16 additions & 0 deletions src/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import dotenv from 'dotenv'

dotenv.config()

const env = process.env.NODE_ENV || 'development'
const debug = env !== 'production'

export default {
env: env,
debug: debug,
port: process.env.PORT || env === 'production' ? 5000 : 5001,
service: {
key: process.env.SERVICE_API_KEY,
secret: process.env.SERVICE_API_SECRET
}
}
22 changes: 22 additions & 0 deletions src/example.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import axios, { AxiosInstance } from 'axios'

const api: AxiosInstance = axios.create({
baseURL: 'https://example.com/',
timeout: 30000, // 30 secs
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})

export async function apiGetFile (fileName: string) {
const url = `/file/${fileName}`
const result = await api.get(url)
return result
}

export async function apiPostFile (fileName: string, data: any) {
const url = `/file/${fileName}`
const result = await api.post(url, { data })
return result
}
77 changes: 77 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import fastify from 'fastify'
import helmet from 'fastify-helmet'
import cors from 'fastify-cors'
import config from './config'
import { apiGetFile, apiPostFile } from './example'

const app = fastify({ logger: config.debug })

app.register(helmet)
app.register(cors)

app.get('/hello', (req, res) => {
res.status(200).send(`Hello World`)
})

app.get('/file', async (req, res) => {
const fileName = req.query.fileName

if (!fileName || typeof fileName !== 'string') {
res.status(500).send({
success: false,
error: 'Internal Server Error',
message: 'Missing or invalid fileName parameter'
})
}

try {
const file = await apiGetFile(fileName)

res.status(200).send({
success: true,
result: file
})
} catch (error) {
console.error(error)

res.status(500).send({
success: false,
error: 'Internal Server Error',
message: error.message
})
}
})

app.post('/file', async (req, res) => {
const fileName = req.query.fileName

if (!fileName || typeof fileName !== 'string') {
res.status(500).send({
success: false,
error: 'Internal Server Error',
message: 'Missing or invalid fileName parameter'
})
}

try {
const response = await apiPostFile(fileName, req.body)

res.status(200).send({
success: true,
result: response
})
} catch (error) {
console.error(error)

res.status(500).send({
success: false,
error: 'Internal Server Error',
message: error.message
})
}
})

app.listen(config.port, (err, address) => {
if (err) throw err
console.log(`Server listening on ${address}`)
})
50 changes: 50 additions & 0 deletions src/utilities.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
export const capitalize = (value: string): string =>
value
.split(' ')
.map(
(word: string): string =>
word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
)
.join(' ')

export const padLeft = (n: string, length: number, z?: string): string => {
z = z || '0'
n = n + ''
return n.length >= length ? n : new Array(length - n.length + 1).join(z) + n
}

export const padRight = (n: string, length: number, z?: string): string => {
z = z || '0'
n = n + ''
return n.length >= length ? n : n + new Array(length - n.length + 1).join(z)
}

export const getDataString = (func: string, arrVals: Array<any>): string => {
let val = ''
for (let i = 0; i < arrVals.length; i++) val += padLeft(arrVals[i], 64)
const data = func + val
return data
}

export function sanitizeHex (hex: string): string {
hex = removeHexPrefix(hex)
hex = hex.length % 2 !== 0 ? '0' + hex : hex
if (hex) {
hex = addHexPrefix(hex)
}
return hex
}

export function addHexPrefix (hex: string): string {
if (hex.toLowerCase().substring(0, 2) === '0x') {
return hex
}
return '0x' + hex
}

export function removeHexPrefix (hex: string): string {
if (hex.toLowerCase().substring(0, 2) === '0x') {
return hex.substring(2)
}
return hex
}
11 changes: 11 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"lib": ["es2016", "es2017", "es2018"],
"strict": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"resolveJsonModule": true
}
}
6 changes: 6 additions & 0 deletions tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"extends": ["tslint-config-standard"],
"rules": {
"no-empty": false
}
}
Loading

0 comments on commit 1dfd150

Please sign in to comment.