繁体   English   中英

如何从 Node JS 中的 Google Cloud Function 中的云 SQL 中读取数据

[英]How to read data form cloud SQL in Google Cloud Function in Node JS

我是 Google Cloud Function 的新手,我在这里尝试从云 SQL 加载数据,因为我编写了一个代码,它具有数据库连接以及 SQL 查询字符串但是当我尝试测试 function 时,它抛出错误或 Object或者有时它说您没有返回任何数据。 我尝试了很多发送数据的方法,但仍然对我不起作用。 提前致谢。

代码片段,

exports.welcome = async (req, res) => {
  const tag = req?.body?.fulfillmentInfo?.tag;
  let message = tag || req?.query?.message || req?.body?.message || 'Hello World!';

  const pool = mysql.createPool({
    connectionLimit: 1,
    host: '10.30.48.2',
    user: 'root',
    password: 'TEST@TEST',
    database: 'hospital_assist'
  });
  
  const jsonResponse = {
    fulfillment_response: {
      messages: [
        {
          text: {
            //fulfillment text response to be sent to the agent
            text: [`Welcome entry point ${message}`],
          },
        },
      ],
    },
  };

  let qResult = await pool.query('SELECT * FROM Patients;');
  // pool.query('SELECT * FROM Patints', (error, result) => {
  //   console.log(error);
  //   console.log(result);
  //   console.log('In loop');
  //   res.status(200).send(jsonResponse);  
  // });



  // await pool.query('select * from Patients;', (error, results) => {
  //       if (error) {
  //           console.log(error);
  //           res.status(200).send(jsonResponse);
  //       }
  //       qResult = results;
  //       // res.send(results);
  //   });

  console.log(qResult);
  console.log(`In loop ${qResult}`);
  res.status(200).send(JSON.stringify(qResult)); 

  // res.status(200).send(jsonResponse);
};

如果您尝试使用公共 IP 连接到您的实例,则需要指定 Unix 套接字路径,例如,

mysql.createPool({
    user: process.env.DB_USER, // e.g. 'my-db-user'
    password: process.env.DB_PASS, // e.g. 'my-db-password'
    database: process.env.DB_NAME, // e.g. 'my-database'
    // If connecting via unix domain socket, specify the path
    socketPath: "/cloudsql/my-project:us-central1:my-instance",
    // Specify additional properties here.
    ...config,
});

有关详细信息,请参阅文档

对于您的情况,您有几种解决方案,特别推荐 2 种:

  • 使用内部 IP(您当前的代码)。 使用该模式,您可以删除公共 IP 并从 inte.net 中完全隐藏数据库。 要允许 CLoud Functions 访问私有 IP,您必须在无服务器世界(服务器和网络由 Google Cloud 为您管理,因此您不在您的 VPC 中)与您的项目世界(尤其是您的 VPC数据库已连接)。 无服务器 VPC 连接器已为此完成。
  • 借助 Cloud Functions,您可以将内置连接器与 Cloud SQL MySQL (仅在版本 8 中)一起使用。 它打开一个 linux 套接字,您必须使用支持该套接字通信模式的驱动程序/库。 这里的优势是通过内置连接器对数据库通信进行加密。

注意:使用 Cloud SQL public IP 避免在您的 Cloud SQL 数据库上使用 authorized.network 以保持良好的安全级别

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM