将Firebase SDK与Netlify Lambda函数一起使用 [英] Use Firebase SDK with Netlify Lambda Functions

查看:79
本文介绍了将Firebase SDK与Netlify Lambda函数一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个使用React + Firebase + Lambda函数的项目.

I create a project that uses React + Firebase + Lambda Functions.

我的前端有Firebase代码,我需要一些后端来处理一些事件. (阻止用户访问在Firebase中修改数据,但允许该数据由应用程序更新)

I have Firebase code on the front end and I needed a bit of back-end to handle some events. (Prevent users from modifying data in Firebase but allow this data to be updated by the application)

使用Netlify部署应用程序时,我可以使用netlify-lambda访问Amazon Lambda Functions. ( https://www.netlify.com/docs/functions/)

As I use Netlify to deploy my app, I have access to Amazon Lambda Functions with netlify-lambda. (https://www.netlify.com/docs/functions/)

通常一切正常(mailchimp API,snipcart API等...)

Usually everything just works (mailchimp API, snipcart API etc ...)

但是我无法使Firebase正常工作.

But I can not get Firebase working.

我创建了一个具有读写权限的服务帐户.

I created a service account with the rights to write and read.

这是我的lambda函数的代码: (只是一个测试,尝试查看数据库的用户部分.)

Here the code of my lambda function: (Just a test to try to see the users section of the database.)

import firebaseAdmin from 'firebase-admin'
const serviceAccount = require('../utils/FirebaseServiceAccountKey.json')

export function handler (event, context, callback) {
  firebaseAdmin.initializeApp({
    credential: firebaseAdmin.credential.cert(serviceAccount),
    databaseURL: 'https://sample-3615.firebaseio.com'
  })

  const db = firebaseAdmin.database()
  const ref = db.ref('/users')
  let users = {}

  ref.once('value', function (snapshot) {
    console.log(snapshot.val())
    users = snapshot.val()
  })

  callback(null, {
    statusCode: 200,
    body: JSON.stringify({ users })
  })
}

它返回我:TypeError: rtdb.initStandalone is not a function.

我也有很多类似这样的警告:Module not found: Error: Can not resolve 'memcpy'以及其他软件包.

I also have many Warning like this: Module not found: Error: Can not resolve 'memcpy' and for other packages too.

我对组件中的函数的调用:

My call to the function in a Component:

handleClick = (e) => {
    e.preventDefault()

    this.setState({loading: true})
    fetch('/.netlify/functions/score')
      .then(res => res.json())
      .then(json => console.log(json.users))
      .then(() => this.setState({loading: false}))
  }

我不确定问题出在哪里. Webpack?

I'm not sure where the problem comes from. Webpack?

推荐答案

我无法使用Netlify的AWS Lambda运行SDK.

I have not been able to run the SDK with AWS Lambda from Netlify.

要使用Netlify Lambda Functions中的Firebase,我将使用具有管理员权限的REST API.

To use Firebase from Netlify Lambda Functions I am going through the REST API with admin privileges.

https://firebase.google.com/docs/reference/rest/数据库/

它是如此完美地工作.

import { google } from 'googleapis'
import fetch from 'node-fetch'
const serviceAccount = require('../utils/FirebaseServiceAccountKey.json')

const scopes = [
  'https://www.googleapis.com/auth/userinfo.email',
  'https://www.googleapis.com/auth/firebase.database'
]

// Authenticate a JWT client with the service account.
const jwtClient = new google.auth.JWT(
  serviceAccount.client_email,
  null,
  serviceAccount.private_key,
  scopes
)

export function handler (event, context, callback) {
  const res = JSON.parse(event.body)
  // Use the JWT client to generate an access token.
  jwtClient.authorize(async function (error, tokens) {
    if (error) {
      console.log('Error making request to generate access token:', error)
    } else if (tokens.access_token === null) {
      console.log('Provided service account does not have permission to generate access tokens')
    } else {
      const accessToken = tokens.access_token
      const score = await fetch(`https://example-3615.firebaseio.com/scores/${res.uid}/score.json`)
        .then(data => data.json())
        .then(score => score + res.score)

      fetch(`https://example-3615.firebaseio.com/scores/${res.uid}.json?access_token=${accessToken}`, {
        body: JSON.stringify({ score, displayName: res.user.displayName, photoURL: res.user.photoURL }),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        method: 'PATCH'
      })
        .then(() => {
          callback(null, {
            statusCode: 200,
            body: 'Score +1'
          })
        })
    }
  })
}

这篇关于将Firebase SDK与Netlify Lambda函数一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆