fatsify核心功能示例测试!!!

This commit is contained in:
2025-09-21 14:50:41 +08:00
commit 9145aea047
1958 changed files with 230098 additions and 0 deletions

38
node_modules/fastify/examples/asyncawait.js generated vendored Normal file
View File

@@ -0,0 +1,38 @@
'use strict'
const fastify = require('../fastify')({ logger: true })
const schema = {
schema: {
response: {
200: {
type: 'object',
properties: {
hello: {
type: 'string'
}
}
}
}
}
}
function result () {
return Promise.resolve({ hello: 'world' })
}
fastify
.get('/await', schema, async function (req, reply) {
reply.header('Content-Type', 'application/json').code(200)
return result()
})
.get('/', schema, async function (req, reply) {
reply.header('Content-Type', 'application/json').code(200)
return { hello: 'world' }
})
fastify.listen({ port: 3000 }, err => {
if (err) {
throw err
}
})

3
node_modules/fastify/examples/benchmark/body.json generated vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"hello": "world"
}

View File

@@ -0,0 +1,44 @@
'use strict'
const fastify = require('../../fastify')({ logger: false })
const opts = {
schema: {
response: {
200: {
type: 'object',
properties: {
hello: {
type: 'string'
}
}
}
}
}
}
function promiseFunction (resolve) {
setImmediate(resolve)
}
async function asyncHook () {
await new Promise(promiseFunction)
}
fastify
.addHook('onRequest', asyncHook)
.addHook('onRequest', asyncHook)
.addHook('preHandler', asyncHook)
.addHook('preHandler', asyncHook)
.addHook('preHandler', asyncHook)
.addHook('onSend', asyncHook)
fastify.get('/', opts, function (request, reply) {
reply.send({ hello: 'world' })
})
fastify.listen({ port: 3000 }, function (err) {
if (err) {
throw err
}
})

View File

@@ -0,0 +1,52 @@
'use strict'
const fastify = require('../../fastify')({ logger: false })
const opts = {
schema: {
response: {
200: {
type: 'object',
properties: {
hello: {
type: 'string'
}
}
}
}
}
}
fastify
.addHook('onRequest', function (request, reply, done) {
done()
})
.addHook('onRequest', function (request, reply, done) {
done()
})
fastify
.addHook('preHandler', function (request, reply, done) {
done()
})
.addHook('preHandler', function (request, reply, done) {
setImmediate(done)
})
.addHook('preHandler', function (request, reply, done) {
done()
})
fastify
.addHook('onSend', function (request, reply, payload, done) {
done()
})
fastify.get('/', opts, function (request, reply) {
reply.send({ hello: 'world' })
})
fastify.listen({ port: 3000 }, function (err) {
if (err) {
throw err
}
})

47
node_modules/fastify/examples/benchmark/parser.js generated vendored Normal file
View File

@@ -0,0 +1,47 @@
'use strict'
const fastify = require('../../fastify')({
logger: false
})
const jsonParser = require('fast-json-body')
const querystring = require('node:querystring')
// Handled by fastify
// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/json' http://localhost:3000/
// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/jsoff' http://localhost:3000/
fastify.addContentTypeParser('application/jsoff', function (request, payload, done) {
jsonParser(payload, function (err, body) {
done(err, body)
})
})
// curl -X POST -d 'hello=world' -H'Content-type: application/x-www-form-urlencoded' http://localhost:3000/
fastify.addContentTypeParser('application/x-www-form-urlencoded', function (request, payload, done) {
let body = ''
payload.on('data', function (data) {
body += data
})
payload.on('end', function () {
try {
const parsed = querystring.parse(body)
done(null, parsed)
} catch (e) {
done(e)
}
})
payload.on('error', done)
})
// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/vnd.custom+json' http://localhost:3000/
fastify.addContentTypeParser(/^application\/.+\+json$/, { parseAs: 'string' }, fastify.getDefaultJsonParser('error', 'ignore'))
fastify
.post('/', function (req, reply) {
reply.send(req.body)
})
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
})

30
node_modules/fastify/examples/benchmark/simple.js generated vendored Normal file
View File

@@ -0,0 +1,30 @@
'use strict'
const fastify = require('../../fastify')({
logger: false
})
const schema = {
schema: {
response: {
200: {
type: 'object',
properties: {
hello: {
type: 'string'
}
}
}
}
}
}
fastify
.get('/', schema, function (req, reply) {
reply
.send({ hello: 'world' })
})
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
})

91
node_modules/fastify/examples/hooks.js generated vendored Normal file
View File

@@ -0,0 +1,91 @@
'use strict'
const fastify = require('../fastify')({ logger: true })
const opts = {
schema: {
response: {
'2xx': {
type: 'object',
properties: {
hello: {
type: 'string'
}
}
}
}
}
}
const optsPost = {
schema: {
body: {
type: 'object',
required: ['hello'],
properties: {
hello: {
type: 'string'
}
}
},
response: opts.response
}
}
fastify
.addHook('onRequest', function (request, reply, done) {
console.log('onRequest')
done()
})
.addHook('preParsing', function (request, reply, payload, done) {
console.log('preParsing')
done()
})
.addHook('preValidation', function (request, reply, done) {
console.log('preValidation')
done()
})
.addHook('preHandler', function (request, reply, done) {
console.log('preHandler')
done()
})
.addHook('preSerialization', function (request, reply, payload, done) {
console.log('preSerialization', payload)
done()
})
.addHook('onError', function (request, reply, error, done) {
console.log('onError', error.message)
done()
})
.addHook('onSend', function (request, reply, payload, done) {
console.log('onSend', payload)
done()
})
.addHook('onResponse', function (request, reply, done) {
console.log('onResponse')
done()
})
.addHook('onRoute', function (routeOptions) {
console.log('onRoute')
})
.addHook('onListen', async function () {
console.log('onListen')
})
.addHook('onClose', function (instance, done) {
console.log('onClose')
done()
})
fastify.get('/', opts, function (req, reply) {
reply.send({ hello: 'world' })
})
fastify.post('/', optsPost, function (req, reply) {
reply.send({ hello: 'world' })
})
fastify.listen({ port: 3000 }, function (err) {
if (err) {
throw err
}
})

39
node_modules/fastify/examples/http2.js generated vendored Normal file
View File

@@ -0,0 +1,39 @@
'use strict'
const fs = require('node:fs')
const path = require('node:path')
const fastify = require('../fastify')({
http2: true,
https: {
key: fs.readFileSync(path.join(__dirname, '../test/https/fastify.key')),
cert: fs.readFileSync(path.join(__dirname, '../test/https/fastify.cert'))
},
logger: true
})
const opts = {
schema: {
response: {
'2xx': {
type: 'object',
properties: {
hello: {
type: 'string'
}
}
}
}
}
}
fastify
.get('/', opts, function (req, reply) {
reply.header('Content-Type', 'application/json').code(200)
reply.send({ hello: 'world' })
})
fastify.listen({ port: 3000 }, err => {
if (err) {
throw err
}
})

38
node_modules/fastify/examples/https.js generated vendored Normal file
View File

@@ -0,0 +1,38 @@
'use strict'
const fs = require('node:fs')
const path = require('node:path')
const fastify = require('../fastify')({
https: {
key: fs.readFileSync(path.join(__dirname, '../test/https/fastify.key')),
cert: fs.readFileSync(path.join(__dirname, '../test/https/fastify.cert'))
},
logger: true
})
const opts = {
schema: {
response: {
'2xx': {
type: 'object',
properties: {
hello: {
type: 'string'
}
}
}
}
}
}
fastify
.get('/', opts, function (req, reply) {
reply.header('Content-Type', 'application/json').code(200)
reply.send({ hello: 'world' })
})
fastify.listen({ port: 3000 }, err => {
if (err) {
throw err
}
})

53
node_modules/fastify/examples/parser.js generated vendored Normal file
View File

@@ -0,0 +1,53 @@
'use strict'
const fastify = require('../fastify')({ logger: true })
const jsonParser = require('fast-json-body')
const querystring = require('node:querystring')
// Handled by fastify
// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/json' http://localhost:3000/
// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/jsoff' http://localhost:3000/
fastify.addContentTypeParser('application/jsoff', function (request, payload, done) {
jsonParser(payload, function (err, body) {
done(err, body)
})
})
// curl -X POST -d 'hello=world' -H'Content-type: application/x-www-form-urlencoded' http://localhost:3000/
fastify.addContentTypeParser('application/x-www-form-urlencoded', function (request, payload, done) {
let body = ''
payload.on('data', function (data) {
body += data
})
payload.on('end', function () {
try {
const parsed = querystring.parse(body)
done(null, parsed)
} catch (e) {
done(e)
}
})
payload.on('error', done)
})
// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/vnd.custom+json' http://localhost:3000/
fastify.addContentTypeParser(/^application\/.+\+json$/, { parseAs: 'string' }, fastify.getDefaultJsonParser('error', 'ignore'))
// remove default json parser
// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/json' http://localhost:3000/ is now no longer handled by fastify
fastify.removeContentTypeParser('application/json')
// This call would remove any content type parser
// fastify.removeAllContentTypeParsers()
fastify
.post('/', function (req, reply) {
reply.send(req.body)
})
fastify.listen({ port: 3000 }, err => {
if (err) {
throw err
}
})

12
node_modules/fastify/examples/plugin.js generated vendored Normal file
View File

@@ -0,0 +1,12 @@
'use strict'
module.exports = function (fastify, opts, done) {
fastify
.get('/', opts, function (req, reply) {
reply.send({ hello: 'world' })
})
.post('/', opts, function (req, reply) {
reply.send({ hello: 'world' })
})
done()
}

38
node_modules/fastify/examples/route-prefix.js generated vendored Normal file
View File

@@ -0,0 +1,38 @@
'use strict'
const fastify = require('../fastify')({ logger: true })
const opts = {
schema: {
response: {
'2xx': {
type: 'object',
properties: {
greet: { type: 'string' }
}
}
}
}
}
fastify.register(function (instance, options, done) {
// the route will be '/english/hello'
instance.get('/hello', opts, (req, reply) => {
reply.send({ greet: 'hello' })
})
done()
}, { prefix: '/english' })
fastify.register(function (instance, options, done) {
// the route will be '/italian/hello'
instance.get('/hello', opts, (req, reply) => {
reply.send({ greet: 'ciao' })
})
done()
}, { prefix: '/italian' })
fastify.listen({ port: 8000 }, function (err) {
if (err) {
throw err
}
})

38
node_modules/fastify/examples/shared-schema.js generated vendored Normal file
View File

@@ -0,0 +1,38 @@
'use strict'
const fastify = require('../fastify')({ logger: true })
fastify.addSchema({
$id: 'https://foo/common.json',
definitions: {
response: {
$id: '#reply',
type: 'object',
properties: {
hello: {
$id: '#bar',
type: 'string'
}
}
}
}
})
const opts = {
schema: {
response: {
200: { $ref: 'https://foo/common.json#reply' }
}
}
}
fastify
.get('/', opts, function (req, reply) {
reply.send({ hello: 'world' })
})
fastify.listen({ port: 3000 }, err => {
if (err) {
throw err
}
})

20
node_modules/fastify/examples/simple-stream.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
'use strict'
const fastify = require('../fastify')({
logger: false
})
const Readable = require('node:stream').Readable
fastify
.get('/', function (req, reply) {
const stream = Readable.from(['hello world'])
reply.send(stream)
})
fastify.listen({ port: 3000 }, (err, address) => {
if (err) {
throw err
}
fastify.log.info(`server listening on ${address}`)
})

32
node_modules/fastify/examples/simple.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
'use strict'
const fastify = require('../fastify')({
logger: false
})
const schema = {
schema: {
response: {
200: {
type: 'object',
properties: {
hello: {
type: 'string'
}
}
}
}
}
}
fastify
.get('/', schema, function (req, reply) {
reply
.send({ hello: 'world' })
})
fastify.listen({ port: 3000 }, (err, address) => {
if (err) {
throw err
}
})

27
node_modules/fastify/examples/simple.mjs generated vendored Normal file
View File

@@ -0,0 +1,27 @@
// works on Node v14.13.0+
import { fastify } from '../fastify.js'
const app = fastify({
logger: true
})
const schema = {
schema: {
response: {
200: {
type: 'object',
properties: {
hello: {
type: 'string'
}
}
}
}
}
}
app.get('/', schema, async function (req, reply) {
return { hello: 'world' }
})
app.listen({ port: 3000 }).catch(console.error)

79
node_modules/fastify/examples/typescript-server.ts generated vendored Normal file
View File

@@ -0,0 +1,79 @@
/**
* Most type annotations in this file are not strictly necessary but are
* included for this example.
*
* To run this example execute the following commands to install typescript,
* transpile the code, and start the server:
*
* npm i -g typescript
* tsc examples/typescript-server.ts --target es6 --module commonjs
* node examples/typescript-server.js
*/
import fastify, { FastifyInstance, RouteShorthandOptions } from '../fastify'
import { Server, IncomingMessage, ServerResponse } from 'node:http'
// Create an http server. We pass the relevant typings for our http version used.
// By passing types we get correctly typed access to the underlying http objects in routes.
// If using http2 we'd pass <http2.Http2Server, http2.Http2ServerRequest, http2.Http2ServerResponse>
const server: FastifyInstance<
Server,
IncomingMessage,
ServerResponse
> = fastify({ logger: true })
// Define interfaces for our request. We can create these automatically
// off our JSON Schema files (See TypeScript.md) but for the purpose of this
// example we manually define them.
interface PingQuerystring {
foo?: number;
}
interface PingParams {
bar?: string;
}
interface PingHeaders {
a?: string;
}
interface PingBody {
baz?: string;
}
// Define our route options with schema validation
const opts: RouteShorthandOptions = {
schema: {
body: {
type: 'object',
properties: {
pong: {
type: 'string'
}
}
}
}
}
// Add our route handler with correct types
server.post<{
Querystring: PingQuerystring;
Params: PingParams;
Headers: PingHeaders;
Body: PingBody;
}>('/ping/:bar', opts, (request, reply) => {
console.log(request.query) // this is of type `PingQuerystring`
console.log(request.params) // this is of type `PingParams`
console.log(request.headers) // this is of type `PingHeaders`
console.log(request.body) // this is of type `PingBody`
reply.code(200).send({ pong: 'it worked!' })
})
// Start your server
server.listen({ port: 8080 }, (err, address) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`server listening on ${address}`)
})

29
node_modules/fastify/examples/use-plugin.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
'use strict'
const fastify = require('../fastify')({ logger: true })
const opts = {
schema: {
response: {
'2xx': {
type: 'object',
properties: {
hello: {
type: 'string'
}
}
}
}
}
}
fastify.register(require('./plugin'), opts, function (err) {
if (err) {
throw err
}
})
fastify.listen({ port: 3000 }, function (err) {
if (err) {
throw err
}
})