fastify: new cheatsheet

This commit is contained in:
Rico Sta. Cruz 2017-09-21 21:37:13 +08:00
parent 811c2886cc
commit c8d5d4defc
No known key found for this signature in database
GPG Key ID: CAAD38AE2962619A
4 changed files with 211 additions and 13 deletions

View File

@ -5,6 +5,8 @@
"---",
"title: {basename|capitalize}",
"category: Ruby",
"layout: 2017/sheet",
"updated: DATE",
"---"
]
}

11
camp.md
View File

@ -15,14 +15,18 @@ Getting started
### Quick start
{: .-prime}
#### app.js
{: .-file}
```js
// app.js
const Camp = require('camp')
const camp = Camp.start({ port: 1234 })
```
#### web/index.html
{: .-file}
```html
<!-- web/index.html -->
<!doctype html>
<body>Hello world!</body>
```
@ -31,8 +35,9 @@ Camp serves files in `web/` by default.
### Routes
#### Handles `/search?q=rainbows`
```js
// /search?q=rainbows
camp.path('/search', (req, res) => {
const q = res.query.q
res.json({ results: ··· })

182
fastify.md Normal file
View File

@ -0,0 +1,182 @@
---
title: Fastify
category: JavaScript libraries
layout: 2017/sheet
updated: 2017-09-21
intro: |
[Fastify](https://github.com/fastify/fastify) lets you create HTTP servers in Node.js with good performance. This guide targets fastify v0.28.x.
---
### Hello world
{: .-prime}
```js
const fastify = require('fastify')()
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
fastify.listen(3000, err => {
if (err) throw err
console.log(`server listening on ${fastify.server.address().port}`)
})
```
### Register
#### app.js
```js
fastify.register(require('./route')), err => {
if (err) throw err
})
```
#### route.js
```js
function (fastify, opts, next) {
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
})
```
See: [Register](https://github.com/fastify/fastify/blob/master/docs/Getting-Started.md#register)
### Register with prefix
```js
fastify.register(
require('./route'),
{ prefix: '/v1' }
)
```
This prefixes all routes in that module.
## Routes
### Writing routes
```js
fastify.route({
method: 'GET',
url: '/',
schema: { ··· },
handler: (req, reply) => { ··· }
beforeHandler: (req, reply, done) => { ··· }
})
```
### Shorthand declarations
```js
fastify.get(path, [options], handler)
fastify.head(···)
fastify.post(···)
fastify.put(···)
fastify.delete(···)
fastify.options(···)
fastify.patch(···)
```
### Async/await
```js
fastify.get('/', options, async (req, reply) => {
return data
// or
reply.send(data)
})
```
When using async functions, you can either `return` data or use `reply.send`.
## Request/reply
### Request
```js
request.query
request.body
request.params
request.headers
request.req // Node.js core
request.log.info('hello')
```
See: [Request](https://github.com/fastify/fastify/blob/master/docs/Request.md)
### Reply
#### Response headers
```js
reply.code(404)
reply.header('Content-Type', 'text/html')
reply.type('text/html')
```
#### Redirects
```js
reply.redirect('/foo')
reply.redirect(302, '/foo')
```
#### Sending
```js
reply.send(payload)
reply.sent // → true|false
```
See: [Reply](https://github.com/fastify/fastify/blob/master/docs/Reply.md)
### JSON schema
#### Define a JSON schema
```js
const schema = {
querystring: {
name: { type: 'string' },
excitement: { type: 'integer' }
},
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
}
```
#### Pass it to the route
```js
fastify.get('/', { schema }, (req, reply) => {
···
})
```
{: data-line="1"}
#### or (same as above)
```js
fastify.route({
method: 'GET',
url: '/',
schema,
handler: (req, reply) => { ··· }
})
```
{: data-line="4"}
By defining a JSON schema, you get validation and improved performance.
See: [Validation and serialize](https://github.com/fastify/fastify/blob/master/docs/Validation-And-Serialize.md)

29
go.md
View File

@ -12,8 +12,10 @@ updated: 2017-09-15
### Hello world
{: .-prime}
#### hello.go
{: .-file}
```go
// hello.go
package main
import "fmt"
@ -36,14 +38,16 @@ Or try it out in the [Go repl](https://repl.it/languages/go), or [A Tour of Go](
### Variables
#### Variable declaration
```go
// Variable declaration
var msg string
msg = "Hello"
```
#### Shortcut of above (Infers type)
```go
// Shortcut of above (Infers type)
msg := "Hello"
```
@ -75,16 +79,18 @@ Strings are of type `string`.
### Numbers
#### Typical types
```go
// Typical types:
num := 3 // int
num := 3. // float64
num := 3 + 4i // complex128
num := byte('a') // byte (alias for uint8)
```
#### Other types
```go
// Other types:
var u uint = 7 // uint (unsigned)
var p float32 = 22.7 // 32-bit float
```
@ -339,25 +345,28 @@ See: [Buffered channels](https://tour.golang.org/concurrency/3)
### Closing channels
#### Closes a channel
```go
// Closes a channel
ch <- 1
ch <- 2
ch <- 3
close(ch)
```
{: data-line="5"}
{: data-line="4"}
#### Iterates across a channel until its closed
```go
// Iterates across a channel until its closed
for i := range ch {
···
}
```
{: data-line="2"}
{: data-line="1"}
#### Closed if `ok == false`
```go
// Closed if ok == false
v, ok := <- ch
```