从云存储获取一些元数据到云功能

时间:2021-03-02 15:03:00

标签: firebase express google-cloud-functions google-cloud-storage web3js

我想从我的云存储中获取一个 json 文件以在云功能中使用(这是在“/post-account”路径中)。虽然,我不确定我是否做对了,因为错误日志打印出 web3 无法在没有 abi(json 接口)的情况下实例化合同。

我只需要一些用于云功能的硬编码元数据。我尝试使用函数目录本地的 json 文件进行部署,并在 index.js 中要求,这不起作用。

我可以尝试将整个 json 接口作为 var 复制到 index.js 中,但这是数千行元数据。

index.js

'use strict';
const Web3 = require('web3');
const Contract = require('web3-eth-contract');
const axios = require('axios')
const fs = require('fs');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const express = require('express');
const cookieParser = require('cookie-parser')();
const cors = require('cors');
const app = express();


//options for cors midddleware
const options = {
  allowedHeaders: [
    'Authorization',
    'Origin',
    'X-Requested-With',
    'Content-Type',
    'Accept',
    'X-Access-Token',
  ],
  credentials: true,
  methods: 'GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE',
  origin: 'https://test-cf-97bfc.web.app',
  preflightContinue: false,
};

// set headers for app.
app.use(function (req, res, next) {

  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', 'https://test-cf-97bfc.web.app');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  next();
});


// Express middleware that validates Firebase ID Tokens passed in the Authorization HTTP header.
// The Firebase ID token needs to be passed as a Bearer token in the Authorization HTTP header like this:
// `Authorization: Bearer <Firebase ID Token>`.
// when decoded successfully, the ID Token content will be added as `req.user`.
const validateFirebaseIdToken = async (req, res, next) => {
  console.log('Check if request is authorized with Firebase ID token');

  if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
    !(req.cookies && req.cookies.__session)) {
    console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.',
      'Make sure you authorize your request by providing the following HTTP header:',
      'Authorization: Bearer <Firebase ID Token>',
      'or by passing a "__session" cookie.');
    res.status(403).send('Unauthorized');
    return;
  }

  let idToken;
  if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
    console.log('Found "Authorization" header');
    // Read the ID Token from the Authorization header.
    idToken = req.headers.authorization.split('Bearer ')[1];
  } else if (req.cookies) {
    console.log('Found "__session" cookie');
    // Read the ID Token from cookie.
    idToken = req.cookies.__session;
  } else {
    // No cookie
    res.status(403).send('Unauthorized');
    return;
  }

  try {
    const decodedIdToken = await admin.auth().verifyIdToken(idToken);
    console.log('ID Token correctly decoded', decodedIdToken);
    req.user = decodedIdToken;
    next();
    return;
  } catch (error) {
    console.error('Error while verifying Firebase ID token:', error);
    res.status(403).send('Unauthorized');
    return;
  }
};




app.use(cors(options))
app.use(cookieParser);
app.use(validateFirebaseIdToken);

app.get('/hello', (req, res) => {
  // @ts-ignore
  res.send(`Hello ${req.user.email}`);
});



app.post('/post-account', async (req, res) => {
  const { account, price } = req.body;
  console.log('account' + account);
  console.log('price' + price);
  //changing to matic node
  const web3 = new Web3.providers.HttpProvider('https://ropsten.infura.io/v3/09cbbdd922284d95a70c627ddf29012d');
  const address = "0xE981aFEeA8E3dB77003C1D56e7c1D42e470Ea775";

//fetch json from cloud storage. Incorrect?
  const abi = axios.get('https://firebasestorage.googleapis.com/v0/b/test-cf-97bfc.appspot.com/o/abis%2Fabi.json?alt=media&token=26bb0e2f-872c-4ee9-ac0f-525b9d84af39')

  console.log('after artifact call');
  Contract.setProvider(web3);
  //error here.
  const contract = new Contract(abi, address);

  await contract.methods.totalSupply().call( function(error, result){
    if  (error) {
      console.log(error);
      res.status(400).end;
    }
    else if (result) {
      res.status(200).json({ txResolved: "NFT awarded post", account: account, currentSupply: result  })
    }
});






});




exports.testAPI = functions.https.onRequest(app);




1 个答案:

答案 0 :(得分:1)

在您可以从云存储中获取任何文件之前,请检查 IAM 政策并测试您是否可以访问它。如果 Cloud Function 与 Cloud Storage 文件存在于同一项目中,则 auth 应该没有问题,除非您将这些规则修改为更严格。如果您需要微调该功能的网络访问,您可以查看这些链接 for VPC networks for general networks

在云函数中,您可以使用 npm @google-cloud/storage 从云存储中获取文件。您可以在文档 link

中获得类似 show 的文件
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

file.get(function(err, file, apiResponse) {
  // file.metadata` has been populated.
});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.get().then(function(data) {
  const file = data[0];
  const apiResponse = data[1];
  // Code to use json file
});

请记住在您的 package.json

中包含依赖项
  "dependencies": {
    "@google-cloud/storage": "^5.8.1"
  }