▶ FLY
, a serverless framwork for back-end development.
- Functional: Everything is function
- Lightweight: Write service in one file
- Yielding: Very flexible
Features
- Hot Reload: Develop back-end with hot-reload
- Simple Inject: Call functions without path. Inject function, module and files
- Live Debug: Live debug withot restart tto solve problem quickly
Installation
Require node >= 10
$ yarn add fly
Quick start
Example
login.js
module.exports = {
configHttp: {
method: 'post',
path: '/api/login'
},
async main ({ body }, { db, config, fly }) {
fly.info(`user login: ${body.user}`)
const user = await db.query('login query')
return {
status: 200,
body: user
}
}
}
Run with fly
Run with HTTP service
$ fly run http↙
┌────────┬────────────────┬────────┐
│ Method │ Path │ Fn │
│ GET │ / │ index │
└────────┴────────────────┴────────┘
[SERVICE] Http Server
NAME: project
TYPE: http
ADDRESS: http://127.0.0.1:5000
PID: 55195
ENV: development
Direct call in CLI
$ fly call login -d 'user=xx&pass=xx'
Definitions
Function
Function Definition
extends: String
decorator: String
main: Function
props:
validate: Function
config<Event>: Object | Boolean | Function
before<Event>: Function | String | Array
after<Event>: Function | String | Array
validate<Event>: Function
catch<Event>: Function | String | Array
props<Event>: Object
Context
eventId: String
eventType: String
originalEvent: Event
parentEvent: Event
fly:
call: Function
find: Function
get: Function
info: Function
warn: Function
error: Function
env: String
@module:
$function: Function
<function>: Function
Validate
Define validate props
or propsHttp
to validate specified main event or http event, throw FlyValidateError
if validate failed.
Config
type: String,
array: Boolean
props: Object
empty: Boolean
pattern: Regexp
enum: Array[String]
format: String | Array | Function
default: String
message: String
Also support name: type
as simple one-line validate for optional validate
FlyValidateError
{
name: "FlyValidateError",
message: "validate failed: message1, message2",
isValidateError: true,
errors: [
{
name: "filed1",
input: "input value",
type: "string",
message: "filed1 invalid"
}
]
}
Command Usage
▶ FLY 4.x.x
Usage:
fly <command> [--options]
Commands:
help Show help
call <fn> Call function
<fn> Function name to call
--type string Set event type: such as http
--data,-d string Event data, support JSON and URL-QUERY-ENCODED
--timeout,-t number Execution timeout
--error,-e Show full error
debug <service> Debug online server
<service> Service type
--filter,-f string
get <fn> Get function info
<fn> Function name
list [type] List functions
log [service] Show service log
new [dir] Create new fly project
[dir] Dir name
--force Force create when dir exists
--source,-s string Select source to create. support: http (default), project
run [service] Run service in foregroud
--instance,-i number The instance number
--bind,-b string Bind address
--port,-p number Bind port
start [service] Start service as daemon
status [service] Show service status
stop [service] Stop service
reload [service] Reload service
restart [service] Restart service
test [fn] Test functions
<fn> Function name
--timeout number
Event can be anything, but must can be JSONify
Events
HTTP
Http Event
method: String
path: String
origin: String
host: String
domain: String
url: String
protocol: String
port: Number
ip: String
headers: Object
body: Object
files: Object
query: Object
search: String
cookies: Object
Http Config
method: String
path: String
domain: String | Array
cache: Boolean | Number
cors: Boolean | String
origin: String
headers: String
methods: String
upload:
allowTypes: Array
maxSize: Number
Command
Command Event
args: Object
params: Object
Command Config
_: String
args: Object
alias: Object
descriptions: Object
_: String
<param>: String
<args>: String
Command Example
module.exports = {
main () {
const command = event.params.command
const showFull = event.args.full
},
configCommand: {
_: 'help <command>',
args: {
'--full': Boolean
},
alias: {
'--full': '-f'
},
descriptions: {
_: 'Show help for commands',
'<help>': 'Command name'
'--full': 'Show full descriptions'
}
}
}
Cron
Cron Event
time: timestamp
Cron Config
time: '* * * * *'
timeout: 60
Cron Example
module.exports = {
main() {
},
configCron: {
time: '*/30 * * * *'
}
}
Error
Error handle Example
Example to handle error with Sentry
const Sentry = require('@sentry/node')
Sentry.init({
dsn: 'http://appkey@sentry.io'
})
module.exports = {
configError: true,
main (event) {
const err = event
if (err instanceof Error) {
Sentry.captureException(err)
} else if (typeof err !== 'undefined') {
Sentry.captureMessage(util.inspect(err, { depth: null, breakLength: Infinity }))
}
}
}
Startup
Connect db When app startup
module.exports = {
configStartup: true,
async main (){
ctx.db = await DB.connect()
console.log('db connected')
}
}
Shutdown
Delete tmp files when shutdown
module.exports = {
configShutdown: true,
main () {
return deleteTempFiles()
}
}
fly.yml
Optional. You can place fly.yml
in directory to overwrite funciton's config
fly.yml
project:
ignore:
- "example/**"
service:
http:
port: 6000
name: 'My http server'
http:
login:
method: post
path: /api/login
cors: true
Test
You can write <name>.test.js
in same folder then run fly test
it will test automatically
Setup a test
index.test.js
index
.test.js file name is same like index.js
or index.file.js
, keep them in same folder
const assert = require('assert')
module.exports = {
tests: [{
name: 'Check result code',
event: {},
test (result) {
assert.strictEqual(result.code, 0)
}
}]
}
Execute test
$ fly test
◼︎ 2 functions to test
√ [1] +index 1/1 passed
√ 1) Check code === 0 (2ms)
√ [2] +userLogin 2/2 passed
√ 1) status === 1 (1ms)
√ 2) invalid username trigger validate error (1ms)
√ 2/2 functions passed
API
You can use in Nodejs and call fly function directly
Usage
const Fly = require('node-fly')
const fly = new Fly('/dir')
await fly.call('test', {host: 'api.com'})
LICENSE
Copyright (c) 2019 hfcorriez hfcorriez@gmail.com
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.