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

Firebase 从云存储到云功能获取一些元数据,firebase,express,google-cloud-functions,google-cloud-storage,web3js,Firebase,Express,Google Cloud Functions,Google Cloud Storage,Web3js,我想从我的云存储中获取一个json文件,以便在云函数中使用(这是在“/post account”路径中)。尽管如此,我不确定我是否做得正确,因为错误日志显示,没有abi(json接口),web3无法实例化合同 我只需要一些云函数的硬编码元数据。我曾尝试将json文件本地部署到函数dir,但在index.js中,这不起作用 我可以尝试将整个json接口作为var复制到index.js中,但这是数千行元数据 index.js 'use strict'; const Web3 = require('w

我想从我的云存储中获取一个json文件,以便在云函数中使用(这是在“/post account”路径中)。尽管如此,我不确定我是否做得正确,因为错误日志显示,没有abi(json接口),web3无法实例化合同

我只需要一些云函数的硬编码元数据。我曾尝试将json文件本地部署到函数dir,但在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);




“严格使用”;
const Web3=require('Web3');
const Contract=require('web3-eth-Contract');
常量axios=require('axios')
常数fs=要求('fs');
const functions=require('firebase-functions');
const admin=require('firebase-admin');
admin.initializeApp();
const express=require('express');
const cookieParser=require('cookie-parser')();
const cors=需要(“cors”);
常量app=express();
//cors Middleware的选项
常量选项={
允许的标题:[
“授权”,
“起源”,
“X-request-With”,
“内容类型”,
“接受”,
“X-Access-Token”,
],
证书:正确,
方法:“GET、HEAD、OPTIONS、PUT、PATCH、POST、DELETE”,
来源:'https://test-cf-97bfc.web.app',
preflightContinue:false,
};
//设置应用程序的标题。
应用程序使用(功能(请求、恢复、下一步){
//您希望允许连接的网站
res.setHeader('Access-Control-Allow-Origin','https://test-cf-97bfc.web.app');
//请求您希望允许的方法
res.setHeader('Access-Control-Allow-Methods'、'GET、POST、OPTIONS、PUT、PATCH、DELETE');
//您希望允许的请求头
res.setHeader('Access-Control-Allow-Headers','X-request-With,content-type');
//如果您需要网站在发送的请求中包含cookie,请设置为true
//到API(例如,如果您使用会话)
res.setHeader('Access-Control-Allow-Credentials',true);
//传递到中间件的下一层
next();
});
//验证在授权HTTP头中传递的Firebase ID令牌的Express中间件。
//Firebase ID令牌需要作为承载令牌在授权HTTP头中传递,如下所示:
//“授权:持票人”。
//解码成功后,ID令牌内容将添加为“req.user”。
const VALIDATEFIREASEIDTOKEN=异步(请求、恢复、下一步)=>{
log('检查请求是否使用Firebase ID令牌授权');
if((!req.headers.authorization | |!req.headers.authorization.startsWith('Bearer'))&&
!(请求cookies和请求cookies.\uuu会话)){
console.error('授权标头中没有作为承载令牌传递Firebase ID令牌。',
'请确保通过提供以下HTTP标头来授权您的请求:',
“授权:持票人”,
'或通过传递一个“uu会话”cookie.”);
res.status(403).发送(“未授权”);
返回;
}
让idToken;
if(req.headers.authorization&&req.headers.authorization.startsWith('Bearer')){
log('Found“Authorization”header');
//从授权标头读取ID令牌。
idToken=req.headers.authorization.split('Bearer')[1];
}else if(请求cookies){
log('Found“\uuuu session”cookie');
//从cookie中读取ID令牌。
idToken=请求cookies.\uuuu会话;
}否则{
//没有饼干
res.status(403).发送(“未授权”);
返回;
}
试一试{
const decodedIdToken=wait admin.auth().verifyIdToken(idToken);
log('ID令牌正确解码',decodedIdToken);
req.user=decodedIdToken;
next();
返回;
}捕获(错误){
console.error('验证Firebase ID令牌时出错:',错误);
res.status(403).发送(“未授权”);
返回;
}
};
应用程序使用(cors(选项))
应用程序使用(cookieParser);
应用程序使用(ValidateFireBaisedToken);
app.get('/hello',(req,res)=>{
//@ts忽略
res.send(`Hello${req.user.email}`);
});
app.post('/post account',异步(请求、回复)=>{
const{account,price}=req.body;
console.log('帐户'+帐户);
console.log(“价格”+价格);
//更改为自动节点
const web3=新的web3.providers.HttpProvider('https://ropsten.infura.io/v3/09cbbdd922284d95a70c627ddf29012d');
const address=“0xE981aFEeA8E3dB77003C1D56e7c1D42e470Ea775”;
//从云存储获取json。不正确?
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')
log('after artifact call');
合同提供商(web3);
//这里有错误。
施工合同=新合同(abi,地址);
等待contract.methods.totalSupply()调用(函数(错误,结果){
如果(错误){
console.log(错误);
资源状态(400)。结束;
}
否则,如果(结果){
res.status(200).json({txResolved:“NFT授予的职位”,帐户:帐户,currentSupply:result})
}
});
});
exports.testAPI=functions.https.onRequest(app);

在您可以从云存储获取任何文件之前,请检查IAM策略并测试您是否可以访问它。如果云函数与云存储文件存在于同一个项目中,那么auth应该不会有问题,除非您修改这些规则使其更加严格。如果需要微调该功能的网络访问,可以查看这些链接并

在云功能中,您可以使用npm从云存储中获取文件。您可以在文档中获得类似show的文件

只需记住在
包.json中包含依赖项

  "dependencies": {
    "@google-cloud/storage": "^5.8.1"
  }

我不知道你想做什么。您可以访问bucket和json文件吗?您尝试使用axios的具体原因是什么?使用bucket访问是否是您的解决方案?可以帮助您访问json的元数据。以下是安装npm的代码:
npm安装--save@google cloud/storage
  "dependencies": {
    "@google-cloud/storage": "^5.8.1"
  }