Skip to content
This repository has been archived by the owner on Jun 22, 2024. It is now read-only.

Feature/fastify examples hello world #25

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@
"infra",
"ideas"
]
},
{
"login": "ghinks",
"name": "Glenn",
"avatar_url": "https://avatars3.githubusercontent.com/u/5049078?v=4",
"profile": "http://glennhinks.com/",
"contributions": [
"code"
]
}
],
"contributorsPerLine": 7
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,5 @@ dist

# ignore lockfiles
package-lock.json
yarn.lock
yarn.lock
./servers/fastify/hello-world/node_modules
2 changes: 2 additions & 0 deletions .markdownlintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
servers/fastify/hello-world/node_modules
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,12 @@ We've documented how to meaningfully contribute in [CONTRIBUTING.md](./CONTRIBUT
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="https://bnb.im"><img src="https://avatars3.githubusercontent.com/u/502396?v=4" width="100px;" alt=""/><br /><sub><b>Tierney Cyren</b></sub></a><br /><a href="https://github.com/node/examples/commits?author=bnb" title="Code">💻</a> <a href="#content-bnb" title="Content">🖋</a> <a href="https://github.com/node/examples/commits?author=bnb" title="Documentation">📖</a> <a href="https://github.com/node/examples/commits?author=bnb" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/mcollina"><img src="https://avatars0.githubusercontent.com/u/52195?v=4" width="100px;" alt=""/><br /><sub><b>Matteo Collina</b></sub></a><br /><a href="#infra-mcollina" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="#ideas-mcollina" title="Ideas, Planning, & Feedback">🤔</a></td>
<td align="center"><a href="https://bnb.im"><img src="https://avatars3.githubusercontent.com/u/502396?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Tierney Cyren</b></sub></a><br /><a href="https://github.com/node/examples/commits?author=bnb" title="Code">💻</a> <a href="#content-bnb" title="Content">🖋</a> <a href="https://github.com/node/examples/commits?author=bnb" title="Documentation">📖</a> <a href="https://github.com/node/examples/commits?author=bnb" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/mcollina"><img src="https://avatars0.githubusercontent.com/u/52195?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Matteo Collina</b></sub></a><br /><a href="#infra-mcollina" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="#ideas-mcollina" title="Ideas, Planning, & Feedback">🤔</a></td>
<td align="center"><a href="http://glennhinks.com/"><img src="https://avatars3.githubusercontent.com/u/5049078?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Glenn</b></sub></a><br /><a href="https://github.com/node/examples/commits?author=ghinks" title="Code">💻</a></td>
</tr>
</table>

<!-- markdownlint-enable -->
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"test:unit": "jest --coverage",
"test:onlychanged": "jest --onlyChanged --coverage",
"test:markdown": "markdownlint . --ignore ./node_modules",
"test:markdown": "markdownlint . ",
"lint": "standard",
"test": "npm run lint && npm run test:unit && npm run test:markdown"
},
Expand Down
131 changes: 131 additions & 0 deletions servers/fastify/hello-world/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
# Fastify Hello World

All the code examples are compliant with the [standard](https://standardjs.com/index.html) linting style. This hello
world example goes into more detail than subsequent examples as it is intended for possible newbies.

## Instructions

Run the fastify [hello-world.js](./hello-world.js) file with nodeJS at the command line.

```shell script
node hello-world.js
```

Fastify is being configured with logging turned on and you should immediately see logs similar to

```text
{"level":30,"time":1597497138242,"pid":49826,"hostname":"mymachineName.local","msg":"Server listening at http://127.0.0.1:3000"}
{"level":30,"time":1597497138243,"pid":49826,"hostname":"mymachineName.local","msg":"server listening on 3000"}
```

## Testing

Either use [curl](https://curl.haxx.se/) on the command line

```shell script
curl http://localhost:3000
```

or paste this into the browser of your choice

```shell script
http://localhost:3000/
```

you should get the hello world response. The server is responding on the root path with a JSON object

```json
{
"hello": "world"
}
```

The format of response will vary depending on your browser and installed plugins.

## Description

Lets look at what is going on here.

```javascript
// Require the framework and instantiate it
const fastify = require('fastify')({ logger: true })

// Declare a route
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})

fastify.listen(APP_PORT)
```

**Fastify** is required into the application and called immediately with a configuration object. The object sets fastify's
logging to true.

```javascript
const fastify = require('fastify')({ logger: true })
```

This could equally be written as

```javascript
const fastifyServer = require('fastify');
const fastify = fastifyServer({
logger: true
})
```

The next thing is a **route** is declared.

```javascript
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
```

This is adding a route to base path '/' that will handle **get** requests on that path. The handling function takes two arguements.
These are [request](https://www.fastify.io/docs/latest/Request/) and [reply](https://www.fastify.io/docs/latest/Reply/).
Note that the reply object is simply returned and that the handling function is declared as **async**

Lets see how the server is being started

```javascript
fastify.listen(APP_PORT)
```

The **listen** function is called upon fastify and provided with a port number and a callback.

## Hello World, with an asynchronous response

The hello-world.js example responded synchronously but what if the reply could not be made synchronously and depended
on other asynchronous services.
To simulate an asynchronous response the [hello-world-async.js](./hello-world-async.js) route uses a timer with a 2
seconds timeout.

```javascript
fastify.get('/', async (request, reply) => {
await setTimeoutPromise(2000)
reply.send({
"hello": "world"
})
})
```

Whats going on here? The route handler sets a timer to simulate asynchronous behavior. In addition the call to fastify
is provided with no callback. When no callback is given fastify returns a promise. We are now starting fastify within an
asynchronous function.

```javascript

// Run the server!
const start = async () => {
try {
// if no callback is give a promise is returned
await fastify.listen(3000)
fastify.log.info(`server listening on ${fastify.server.address().port}`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
fastify.log.info(`server listening on ${fastify.server.address().port}`)

This log line should not be needed, this info is logged by fastify itself now

} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
```
25 changes: 25 additions & 0 deletions servers/fastify/hello-world/hello-world-async.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Require the framework and instantiate it
const util = require('util')
const setTimeoutPromise = util.promisify(setTimeout)
const fastify = require('fastify')({ logger: true })

// Declare a route
fastify.get('/', async (request, reply) => {
await setTimeoutPromise(2000)
reply.send({
"hello": "world"
})
})

// Run the server!
const start = async () => {
try {
// if no callback is give a promise is returned
await fastify.listen(3000)
fastify.log.info(`server listening on ${fastify.server.address().port}`)
Copy link
Member

@mcollina mcollina Aug 21, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
fastify.log.info(`server listening on ${fastify.server.address().port}`)

This log line should not be needed, this info is logged by fastify itself now

} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
10 changes: 10 additions & 0 deletions servers/fastify/hello-world/hello-world.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Require the framework and instantiate it
const fastify = require('fastify')({ logger: true })
const APP_PORT = 3000

// Declare a route
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})

fastify.listen(APP_PORT)
15 changes: 15 additions & 0 deletions servers/fastify/hello-world/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "hello-world",
"version": "1.0.0",
"description": "All the code examples are compliant with the [standard](https://standardjs.com/index.html) linting style. This hello world example goes into more detail than subsequent examples as it is intended for possible newbies.",
"main": "hello-world.js",
"scripts": {
"start": "node hello-world.js"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"fastify": "^3.2.1"
}
}