Last active
July 4, 2021 07:38
-
-
Save shwei/d34c7383a117451c07dc701ad12482f1 to your computer and use it in GitHub Desktop.
Use fastify in firebase function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const functions = require('firebase-functions'); | |
const fastify = require('./fastify'); | |
exports.greetFromFastify = functions.https.onRequest(fastify); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const http = require('http'); | |
const Fastify = require('fastify'); | |
let handleRequest = null; | |
const serverFactory = (handler, opts) => { | |
handleRequest = handler; | |
console.log('server factory opts: %j', opts); | |
return http.createServer(); | |
}; | |
const fastify = Fastify({ | |
serverFactory, | |
logger: true, | |
// skipHandleTrustProxy: true // proposed addition to the options | |
}); | |
fastify.get('/get', (req, reply) => { | |
reply.send('[Fastify] Response from GET request'); | |
}); | |
fastify.post('/post', (req, reply) => { | |
reply.send('[Fastify] Response from POST request'); | |
}); | |
module.exports = (req, res) => { | |
console.log('req.ip: %s', req.ip); // req.ip: 127.0.0.1 | |
/* | |
Without the next line, an error would occur | |
error: /Users/shwei/Work/workspace/cf-fastify-restify-express/functions/node_modules/fastify/fastify.js:249 | |
req.ip = req.connection.remoteAddress | |
^ | |
TypeError: Cannot set property ip of [object Object] which has only a getter | |
at _ipAsRemoteAddress (/Users/shwei/Work/workspace/cf-fastify-restify-express/functions/node_modules/fastify/fastify.js:249:12) | |
*/ | |
req = Object.assign({ip: ''}, {...req}); | |
fastify.ready(err => { | |
if (err) throw err; | |
handleRequest(req, res); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any Suggestion/help how to send data in a post request, even defining a schema also is not helping???
Above example works only if you don't send any json data in body. Once you send the it gives error:
payload.setEncoding('utf8')