Giter VIP home page Giter VIP logo

fastify-cli's Introduction

fastify-cli

CI NPM version js-standard-style

Command line tools for Fastify. Generate, write, and run an application with one single command!

Install

npm install fastify-cli --global

Usage

fastify-cli offers a single command line interface for your Fastify project:

$ fastify

Will print an help:

Fastify command line interface, available commands are:

  * start                 start a server
  * eject                 turns your application into a standalone executable with a server.(js|ts) file being added
  * generate              generate a new project
  * generate-plugin       generate a new plugin project
  * generate-swagger      generate Swagger/OpenAPI schema for a project using @fastify/swagger
  * readme                generate a README.md for the plugin
  * print-routes          prints the representation of the internal radix tree used by the router, useful for debugging.
  * print-plugins         prints the representation of the internal plugin tree used by avvio, useful for debugging.
  * version               the current fastify-cli version
  * help                  help about commands

Launch 'fastify help [command]' to know more about the commands.

The default command is start, you can hit

  fastify start plugin.js

to start plugin.js.

start

You can start any Fastify plugin with:

$ fastify start plugin.js

A plugin can be as simple as:

// plugin.js
module.exports = function (fastify, options, next) {
  fastify.get('/', function (req, reply) {
    reply.send({ hello: 'world' })
  })
  next()
}

If you are using Node 8+, you can use Promises or async functions too:

// async-await-plugin.js
module.exports = async function (fastify, options) {
  fastify.get('/', async function (req, reply) {
    return { hello: 'world' }
  })
}

For a list of available flags for fastify start see the help: fastify help start.

If you want to use custom options for the server creation, just export an options object with your route and run the cli command with the --options flag. These options also get passed to your plugin via the options argument.

// plugin.js
module.exports = function (fastify, options, next) {
  fastify.get('/', function (req, reply) {
    reply.send({ hello: 'world' })
  })
  next()
}

module.exports.options = {
  https: {
    key: 'key',
    cert: 'cert'
  }
}

And if you are using EcmaScript Module format:

export default async function plugin (fastify, options) {
  // Both `/foo` and `/foo/` are registered
  fastify.get('/foo/', async function (req, reply) {
    return 'foo'
  })
}

export const options = {
  ignoreTrailingSlash: true
}

If you want to use custom options for your plugin, just add them after the -- terminator. If used in conjunction with the --options argument, the CLI arguments take precedence.

// plugin.js
module.exports = function (fastify, options, next) {
  if (option.one) {
    //...
  }
  //...
  next()
}
$ fastify start plugin.js -- --one

Modules in EcmaScript Module format can be used on Node.js >= 14 or >= 12.17.0 but < 13.0.0'

// plugin.js
export default async function plugin (fastify, options) {
  fastify.get('/', async function (req, reply) {
    return options
  })
}

This works with a .js extension if you are using Node.js >= 14 and the nearest parent package.json has "type": "module" (more info here). If your package.json does not have "type": "module", use .mjs for the extension (plugin.mjs in the above example).

Options

You can pass the following options via CLI arguments. You can also use --config or -c flag to pass a configuration file that exports all the properties listed below in camelCase convention. In case of collision (i.e., An argument existing in both the configuration file and as a command-line argument, the command-line argument is given the priority). Every option has a corresponding environment variable:

Description Short command Full command Environment variable
Path to configuration file that can be used to manage the options listed below -c --config FASTIFY_CONFIG or CONFIG
Port to listen on (default to 3000) -p --port FASTIFY_PORT or PORT
Address to listen on -a --address FASTIFY_ADDRESS
Socket to listen on -s --socket FASTIFY_SOCKET
Module to preload -r --require FASTIFY_REQUIRE
ES Module to preload -i --import FASTIFY_IMPORT
Log level (default to fatal) -l --log-level FASTIFY_LOG_LEVEL
Path to logging configuration module to use -L --logging-module FASTIFY_LOGGING_MODULE
Start Fastify app in debug mode with nodejs inspector -d --debug FASTIFY_DEBUG
Set the inspector port (default: 9320) -I --debug-port FASTIFY_DEBUG_PORT
Set the inspector host to listen on (default: loopback address or 0.0.0.0 inside Docker or Kubernetes) --debug-host FASTIFY_DEBUG_HOST
Prints pretty logs -P --pretty-logs FASTIFY_PRETTY_LOGS
Watch process.cwd() directory for changes, recursively; when that happens, the process will auto reload -w --watch FASTIFY_WATCH
Ignore changes to the specified files or directories when watch is enabled. (e.g. --ignore-watch='node_modules .git logs/error.log' ) --ignore-watch FASTIFY_IGNORE_WATCH
Prints events triggered by watch listener (useful to debug unexpected reload when using --watch ) -V --verbose-watch FASTIFY_VERBOSE_WATCH
Use custom options -o --options FASTIFY_OPTIONS
Set the prefix -x --prefix FASTIFY_PREFIX
Set the plugin timeout -T --plugin-timeout FASTIFY_PLUGIN_TIMEOUT
Defines the maximum payload, in bytes,
that the server is allowed to accept
--body-limit FASTIFY_BODY_LIMIT
Set the maximum ms delay before forcefully closing pending requests after receiving SIGTERM or SIGINT signals; and uncaughtException or unhandledRejection errors (default: 500) -g --close-grace-delay FASTIFY_CLOSE_GRACE_DELAY

By default fastify-cli runs dotenv, so it will load all the env variables stored in .env in your current working directory.

The default value for --plugin-timeout is 10 seconds. By default --ignore-watch flag is set to ignore `node_modules build dist .git bower_components logs .swp' files.

Containerization

When deploying to a Docker container, and potentially other, containers, it is advisable to set a fastify address of 0.0.0.0 because these containers do not default to exposing mapped ports to localhost.

For containers built and run specifically by the Docker Daemon or inside a Kubernetes cluster, fastify-cli is able to detect that the server process is running within a container and the 0.0.0.0 listen address is set automatically.

Other containerization tools (eg. Buildah and Podman) are not detected automatically, so the 0.0.0.0 listen address must be set explicitly with either the --address flag or the FASTIFY_ADDRESS environment variable.

Fastify version discovery

If Fastify is installed as a project dependency (with npm install --save fastify), then fastify-cli will use that version of Fastify when running the server. Otherwise, fastify-cli will use the version of Fastify included within fastify-cli.

Migrating out of fastify-cli start

If you would like to turn your application into a standalone executable, just add the following server.js:

'use strict'

// Read the .env file.
require('dotenv').config()

// Require the framework
const Fastify = require('fastify')

// Require library to exit fastify process, gracefully (if possible)
const closeWithGrace = require('close-with-grace')

// Instantiate Fastify with some config
const app = Fastify({
  logger: true
})

// Register your application as a normal plugin.
const appService = require('./app.js')
app.register(appService)

// delay is the number of milliseconds for the graceful close to finish
closeWithGrace({ delay: process.env.FASTIFY_CLOSE_GRACE_DELAY || 500 }, async function ({ signal, err, manual }) {
  if (err) {
    app.log.error(err)
  }
  await app.close()
})

// Start listening.
app.listen({ port: process.env.PORT || 3000 }, (err) => {
  if (err) {
    app.log.error(err)
    process.exit(1)
  }
})

generate

fastify-cli can also help with generating some project scaffolding to kickstart the development of your next Fastify application. To use it:

  1. fastify generate <yourapp>
  2. cd yourapp
  3. npm install

The sample code offers you the following npm tasks:

  • npm start - starts the application
  • npm run dev - starts the application with pino-pretty pretty logging (not suitable for production)
  • npm test - runs the tests
  • npm run lint - fixes files accordingly to linter rules, for templates generated with --standardlint

You will find three different folders:

  • plugins: the folder where you will place all your custom plugins
  • routes: the folder where you will declare all your endpoints
  • test: the folder where you will declare all your test

Finally, there will be an app.js file, which is your entry point. It is a standard Fastify plugin and you will not need to add the listen method to run the server, just run it with one of the scripts above.

If the target directory exists fastify generate will fail unless the target directory is ., as in the current directory.

If the target directory is the current directory (.) and it already contains a package.json file, fastify generate will fail. This can be overidden with the --integrate flag:

fastify generate . --integrate

This will add or alter the main, scripts, dependencies and devDependencies fields on the package.json. In cases of file name collisions for any files being added, the file will be overwritten with the new file added by fastify generate. If there is an existing app.js in this scenario, it will be overwritten. Use the --integrate flag with care.

Options

Description Full command
To generate ESM based JavaScript template --esm
Use the TypeScript template --lang=ts, --lang=typescript
Overwrite it when the target directory is the current directory (.) --integrate
For JavaScript template, optionally includes Standard linter to fix code style issues --standardlint

generate-plugin

fastify-cli can help you improve your plugin development by generating a scaffolding project:

  1. fastify generate-plugin <yourplugin>
  2. cd yourplugin
  3. npm install

The boilerplate provides some useful npm scripts:

  • npm run unit: runs all unit tests
  • npm run lint: to check your project's code style
  • npm run test:typescript: runs types tests
  • npm test: runs all the checks at once

readme

fastify-cli can also help with generating a concise and informative readme for your plugin. If no package.json is provided a new one is generated automatically. To use it:

  1. cd yourplugin
  2. fastify readme <path-to-your-plugin-file>

Finally, there will be a new README.md file, which provides internal information about your plugin e.g:

  • Install instructions
  • Example usage
  • Plugin dependencies
  • Exposed decorators
  • Encapsulation semantics
  • Compatible Fastify version

generate-swagger

if your project uses @fastify/swagger, fastify-cli can generate and write out the resulting Swagger/OpenAPI schema for you.

fastify generate-swagger app.js

linting

fastify-cli is unopinionated on the choice of linter. We recommend you to add a linter, like so:

"devDependencies": {
+ "standard": "^11.0.1",
}

"scripts": {
+ "pretest": "standard",
  "test": "tap test/**/*.test.js",
  "start": "fastify start -l info app.js",
  "dev": "fastify start -l info -P app.js",
+ "lint": "standard --fix"
},

Test helpers

When you use fastify-cli to run your project you need a way to load your application because you can run the CLI command. To do so, you can use the this module to load your application and give you the control to write your assertions. These utilities are async functions that you may use with the node-tap testing framework.

There are two utilities provided:

  • build: builds your application and returns the fastify instance without calling the listen method.
  • listen: starts your application and returns the fastify instance listening on the configured port.

Both of these utilities have the function(args, pluginOptions, serverOptions) parameters:

  • args: is a string or a string array within the same arguments passed to the fastify-cli command.
  • pluginOptions: is an object containing the options provided to the started plugin (eg: app.js).
  • serverOptions: is an object containing the additional options provided to fastify server, similar to the --options command line argument
// load the utility helper functions
const { build, listen } = require('fastify-cli/helper')

// write a test
const { test } = require('tap')
test('test my application', async t => {
  const argv = ['app.js']
  const app = await build(argv, {
    extraParam: 'foo'
  })
  t.teardown(() => app.close())

  // test your application here:
  const res = await app.inject('/')
  t.same(res.json(), { hello: 'one' })
})

Log output is consumed by tap. If log messages should be logged to the console the logger needs to be configured to output to stderr instead of stdout.

const logger = {
  transport: {
    target: 'pino-pretty',
    options: {
      destination: 2,
    },
  },
}
const argv = ['app.js']
test('test my application with logging enabled', async t => {
  const app = await build(argv, {}, { logger })
  t.teardown(() => app.close())

  // test your application here:
  const res = await app.inject('/')
  t.same(res.json(), { hello: 'one' })
})

Contributing

If you feel you can help in any way, be it with examples, extra testing, or new features please open a pull request or open an issue.

How to execute the CLI

Instead of using the fastify keyword before each command, use node cli.js
Example: replace fastify start with node cli.js start

License

MIT

fastify-cli's People

Contributors

10xlacroixdrinker avatar alemagio avatar allevo avatar anthonyringoet avatar bcomnes avatar big-kahuna-burger avatar cemremengu avatar delvedor avatar dependabot-preview[bot] avatar dependabot[bot] avatar dottorblaster avatar eomm avatar etino avatar fdawgs avatar francisdaigle avatar gaogao1030 avatar github-actions[bot] avatar greenkeeper[bot] avatar lundibundi avatar madflow avatar mcollina avatar mhamann avatar nemoalex avatar ninjatux avatar nooreldeensalah avatar rommelandrea avatar segevfiner avatar simoneb avatar uzlopak avatar xtx1130 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastify-cli's Issues

lack dependency

the generated plugins/support.js file require fastify-plugin, but it is not included in the dependencies of package.json

Schema check not working ?

I try to write new simple plugin intend for routing and function process, But when i add schema check it does not happen ( no effect with routing )

What going wrong ?

code below i want to check parameter post ( require )

'use strict'

module.exports = function (fastify, opts, next) {

const post_schema = {
	method: 'GET',
	schema: {
		body: {
			type: 'object',
			properties: {
				public_key: { type: 'string' }
			},
			required: ['public_key']
		}
	}
}

  fastify
    .get('/get', { opts } , async function(req, reply) {
      reply.send({ 
      	data: req.query,
      	name: '' 
      }
      	)
    })
    .post('/post', { post_schema, attachValidation: true }, async function (req, reply) {
      reply.send(
      	{ 
      		account_name: req.body 
        })
    })
  next()
}

// If you prefer async/await, use the following
//
// module.exports = async function (fastify, opts) {
//   fastify.get('/', async function (request, reply) {
//     return { root: true }
//   })
// }

Bind 0.0.0.0 in docker env

If you run a Fastify server in Docker by default it will run on the address 127.0.0.1 which is not reachable from outside.
We can add an is docker check and if it is true, use 0.0.0.0 instead of 127.0.0.1.

What do you think?

a new fastify app generator?

Hi all,
I've created a Fastify app generator inspired to this wonderful project and I called it create-fastify-app. Create Fastify App can help a programmer to generate or add plugin to a Fastify project. For now I added these functionalities:

  • Generate a Fastify Project, also from a given swagger file.
  • Generate a service skeleton in existing Fastify Project.
  • Add Cors plugin in existing Fastify Project.
  • Add MongoDB plugin in existing Fastify Project.
  • Add Redis plugin in existing Fastify Project.

I hope to be able to add many other plugins and features!
What do you think? It might be useful to the Fastify community?

Consider removing linter tasks from the generated project

Currently the cli generates a project with the standardjs linting. However, most people is probably using eslint (I suppose). So I believe that the cli should support one of the following:

a) A generator option with eslint config (maybe just use airbnb preset)
b) A bare and unopinionated generator in terms of linting (Simpler)

.gitignore is not copied when using the cli

During testing or when running node ..\cli.js generate directly, the .gitignore file is copied just fine. However,

$ npm install -g fastify-cli
$ fastify generate

does not copy/generate the .gitignore

Any ideas? Possibly related to generify. Will check it out as well.

An in-range update of sinon is breaking the build 🚨

Version 5.0.9 of sinon was just published.

Branch Build failing 🚨
Dependency sinon
Current Version 5.0.8
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

sinon is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 5 commits.

  • 86b930c Update docs/changelog.md and set new release id in docs/_config.yml
  • 033aa60 Add release documentation for v5.0.9
  • 3321085 5.0.9
  • 9f321d5 Update History.md and AUTHORS for new release
  • e862196 Upgrade @std/esm to esm.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

prefix register twice

I'm create project by this command: fastify generate test
and start project by fastify start -l info -P -w app.js -r /chat-api

fastify-cli file start.js line 129 register fastify _routePrefix

if (opts.prefix) {
    pluginOptions.prefix = opts.prefix
    fastify._routePrefix = opts.prefix || ''
}

fastify-autoload options config register prefix again

i have to access app by this url http://127.0.0.1:3000/chat-api/chat-api/example
what i need is http://127.0.0.1:3000/chat-api/example

some env variables doesn't work

Three env variables FASTIFY_PRETTY_LOGS, FASTIFY_OPTIONS, FASTIFY_WATCH doesn't work. they will be override by default values.

Related code:

// run without any command line arg
// $ fastify start app.js
let opts = minimistArgs(args)  // --> contain { pretty-log: false, options: false, watch: fasle }
opts = Object.assign(readEnv(), opts) -> opts will override env

/usr/bin/env: ‘node\r’: No such file or directory

Installed globally via NPM and Yarn, same issue.
When I run any fastify command I get the error:
/usr/bin/env: ‘node\r’: No such file or directory

Arch Linux (Antergos)
Node: 10.11.0
Yarn: 1.12.3
NPM: 6.4.1

CORS support

Could it be possible to add a flag to enable CORS support? Does it makes sense, or is there any other way to have CORS support with fastify-cli? Is it only possible to have CORS support by creating an ad-hoc server?

An in-range update of standard is breaking the build 🚨

Version 12.0.1 of standard was just published.

Branch Build failing 🚨
Dependency standard
Current Version 12.0.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

standard is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 8 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of sinon is breaking the build 🚨

The devDependency sinon was updated from 7.3.1 to 7.3.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

sinon is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 6 commits.

  • 15a9d65 Update docs/changelog.md and set new release id in docs/_config.yml
  • 5d770e0 Add release documentation for v7.3.2
  • 585a1e9 7.3.2
  • b51901d Update CHANGELOG.md and AUTHORS for new release
  • 83861a7 Update Lolex to bring in fix for sinonjs/lolex#232
  • 2430fd9 Documentation (#2004)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Call decorator inside listen.

Hello everyone.
I think that without cli is possible to call a decorator inside the .listener method to start the server.

Is this possible with cli?
Ty!

Tests are failing on windows

Most tests are failing for me due to comparison errors like

test/generate.js .................................... 47/67
  finish succesfully if package.json is there - npm
  not ok \app.js matching
    +++ found
    --- wanted



                      require('fastify-autoload')

                 ts = function (fastify, opts, next) {
                                 code!

                             llowing lines

                     all plugins defined in plugins
              e should be support plugins that are reused


                         _dirname, 'plugins'),
                              n({}, opts)


                   s all plugins defined in services
                           s in one of these

                        __dirname, 'services'),
                              n({}, opts)


                             ext when done


    +'use strict'
    +
    +const path = require('path')
    +const AutoLoad = require('fastify-autoload')
    +
    +module.exports = function (fastify, opts, next) {
    +  // Place here your custom code!
    +
    +  // Do not touch the following lines
    +
    +  // This loads all plugins defined in plugins
    +  // those should be support plugins that are reused
    +  // through your application
    +  fastify.register(AutoLoad, {
    +    dir: path.join(__dirname, 'plugins'),
    +    options: Object.assign({}, opts)
    +  })
    +
    +  // This loads all plugins defined in services
    +  // define your routes in one of these
    +  fastify.register(AutoLoad, {
    +    dir: path.join(__dirname, 'services'),
    +    options: Object.assign({}, opts)
    +  })
    +
    +  // Make sure to call next when done
    +  next()
    +}

The expected stuff is coming out garbled. I am suspecting \r\n situation but I couldn't figure out the reason so shamelessly posting here. 😄

Any ideas?

Watch does not restart the process once it crashes

Message says the process is crashed and waiting for changes to restart however nothing happens after changes. Seeing the comments here, is this a WIP feature? I am using node v8.11.3 on windows 10.

process.on("uncaughtException", err => {
  console.log(err);
  const message = chalk.red(
    "[fastify-cli] app crashed - waiting for file changes before starting..."
  );
  // fastify.close(exit) // It's looks that only happend fastify normally startup. so we should detect fastify is normally runing, it's normally running that graceful exit happen, other case I think it's better immediately exec process.exit(1)
  //setTimeout(exit.bind({ message }), TIMEOUT).unref();
  exit.bind({ message })();
});

Migration

Can we have an example to move a fastify-cli app to standard fastify

error while installing

I was installing fastify globally and at the end, it looks like it got installed successfully but there are some errors logs in between.

Bhavays-MacBook-Air:~ bhavayanand$ sudo npm install fastify-cli --global
Password:
/usr/local/bin/fastify -> /usr/local/lib/node_modules/fastify-cli/cli.js

> [email protected] install /usr/local/lib/node_modules/fastify-cli/node_modules/fsevents
> node install

node-pre-gyp WARN Pre-built binaries not installable for [email protected] and [email protected] (node-v67 ABI, unknown) (falling back to source compile with node-gyp) 
node-pre-gyp WARN Hit error EACCES: permission denied, mkdir '/usr/local/lib/node_modules/fastify-cli/node_modules/fsevents/lib/binding/Release/node-v67-darwin-x64' 
gyp ERR! clean error 
gyp ERR! stack Error: EACCES: permission denied, rmdir 'build'
gyp ERR! System Darwin 17.4.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "clean"
gyp ERR! cwd /usr/local/lib/node_modules/fastify-cli/node_modules/fsevents
gyp ERR! node -v v11.1.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok 
node-pre-gyp ERR! build error 
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js clean' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/fastify-cli/node_modules/fsevents/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:182:13)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:970:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:257:5)
node-pre-gyp ERR! System Darwin 17.4.0
node-pre-gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/fastify-cli/node_modules/fsevents/node_modules/node-pre-gyp/bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /usr/local/lib/node_modules/fastify-cli/node_modules/fsevents
node-pre-gyp ERR! node -v v11.1.0
node-pre-gyp ERR! node-pre-gyp -v v0.10.0
node-pre-gyp ERR! not ok 
Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js clean' (1)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/fastify-cli/node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] install: `node install`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

+ [email protected]
updated 1 package in 19.672s
Bhavays-MacBook-Air:~ bhavayanand$ fastify --version
0.26.1

node version: 11.1.0
npm version: 6.4.1

Thanks

Getting started with a new project

Expected
fastify generate creates a new project as the docs state.

Actual result

--> reading package.json in /Users/benhalverson/projects/fastify-cli-test
ENOENT: no such file or directory, open '/Users/benhalverson/projects/fastify-cli-test/package.json'

The workaround is to create a package.json file first in directory your project will be in
npm init -y

Error: /usr/bin/env: ‘node\r’: No such file or directory

When installing the cli via npm, sudo npm install fastify-cli --global and running fastify generate i get the following error /usr/bin/env: ‘node\r’: No such file or directory
What is wrong?

OS: Ubuntu 18.04
NPM VERSION: v5.4.2
NODE VERSION: v8.7.0

Support for TypeScript template and eject command

Hi, guys. It will be nice to include in fastify-cli support for TypeScript projects.
In order to generate a TS project we need to change some of the current fastify-cli's commands and to add one new:

  • start start a server -> here we can add support for .ts files (auto-discover file extension), add default tsconfig.json file with default compilation rules and use ts-node with inline sourcemap generation to run the code. Notes: Running .ts is not intended for production environment, .ts files will be inside /src folder, as this is a TS standard defacto.
  • generate generate a new project -> we need to add new arg --typescript (-ts) to generate TypeScript project with all dependencies and to add to package.json typings and typescript compiler. In addition we need (just one?) new npm-script to build .ts code.
  • eject ejects the app (new command) -> creates server.ts file and compiles all TypeScript code from src to build (or dist) folder and modifies scripts to use newly generated paths. Note: this command could be used also by JS projects.

In addition to that, what do you think to add one more new npm-script for running debugger in package.json? It would be nice to have it ready inside package.json.

I am looking forward for ideas and I am ready to implement this feature,

An in-range update of request is breaking the build 🚨

☝️ Greenkeeper’s updated Terms of Service will come into effect on April 6th, 2018.

Version 2.84.0 of request was just published.

Branch Build failing 🚨
Dependency request
Current Version 2.83.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

request is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 6 commits.

  • d77c839 Update changelog
  • 4b46a13 2.84.0
  • 0b807c6 Merge pull request #2793 from dvishniakov/2792-oauth_body_hash
  • cfd2307 Update hawk to 7.0.7 (#2880)
  • efeaf00 Fixed calculation of oauth_body_hash, issue #2792
  • 253c5e5 2.83.1

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml
  • The new Node.js version is in-range for the engines in 1 of your package.json files, so that was left alone

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Default test paths for the template

If Fastify assumes the recursive folder structure, why wouldn't change the default test paths from tap test/*.test.js test/*/*.test.js test/*/*/*.test.js to tap test/**/*.test.js for the template, because it ignores nested plugin/service folders

Add "--opts NAME=VALUE" in order to pass the parameters to plugin

as titled

fastify --opts VAR1=value1 --opts VAR2=value2 index.js

index.js

module.exports = async function (fastify, opts) {
  fastify.register(require('fastify-env'), {
    schema: {
      type: 'object',
      required: ['VAR1'],
      properties: {
        VAR1: { type: 'string' },
        VAR2: { type: 'string', default: 'foo-bar' }
      }
    },
    env: false,
    data: [opts, process.env]
  })
    .after(err => {
      if (err) throw err
      console.log(fastify.config) // { VAR1: "value1", VAR2: "value2" }
    })
}

Environment variable FASTIFY_WATCH is not honored

The reason why is because require('dotenv').config() is not called inside the start() function, and therefore

if (opts.watch) {
  return watch(args, opts.ignoreWatch)
}

is never true, unless there is an actual CLI argument set for it.

Unfortunately putting require('dotenv').config() on top of the start() function breaks your test suite. So probably there is something else going on that I'm not aware of.


My .env file looks like this:

FASTIFY_WATCH=true

And I'm starting the server with:

fastify start server.js

PM2

It's possible to use PM2 with fastify-cli?

How do I do Error Reporting?

Hello!

Currently, I am trying to set up Sentry with my fastify server. I am doing the following:

fastify.setErrorHandler(function (error, request, reply) {
  Sentry.captureException(error, { request });
})

However, I noticed that adding this makes the server not respond to the requests. I was wondering if it were possible to add this captureException line but also respond to fastify in the default manner?

More control over logging

@mcollina It seems that we currently need to eject if we want more control over the logger, e.g.:

  • force the pino logger instance so we can use the logger out of fastify context
  • set our own configuration, notably what to redact or serializers

It could be great if that would not be necessary ( an env var for loading a module exporting the logger could be enough, and some example in the Readme )

Generating project does not work with yarn

Hello!

Generating a new project with yarn does not work, because yarn does not include a scripts property to the package.json.

pkg.scripts.test = 'standard && tap test/*.test.js test/*/*.test.js test/*/*/*.test.js'
                     ^
TypeError: Cannot set property 'test' of undefined

works fine with npm

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.