云函数与云 SQL - 属性"socketPath"在类型上不存在



我正在尝试在Firebase Functions上访问我的Google Cloud SQL数据库。我遵循了Google文档,但它不是很好,遗漏了很多信息。

我将文档中的代码添加到我的srcindex.ts文件中并填写了我的数据:

const mysql = require('mysql');
const connectionName =
  process.env.INSTANCE_CONNECTION_NAME || 'test';
const dbUser = process.env.SQL_USER || 'test';
const dbPassword = process.env.SQL_PASSWORD || 'test';
const dbName = process.env.SQL_NAME || 'test';
const mysqlConfig = {
  connectionLimit: 1,
  user: dbUser,
  password: dbPassword,
  database: dbName,
};
if (process.env.NODE_ENV === 'production') {
  mysqlConfig.socketPath = `/cloudsql/${connectionName}`;
}
// Connection pools reuse connections between invocations,
// and handle dropped or expired connections automatically.
let mysqlPool;
exports.mysqlDemo = (req, res) => {
  // Initialize the pool lazily, in case SQL access isn't needed for this
  // GCF instance. Doing so minimizes the number of active SQL connections,
  // which helps keep your GCF instances under SQL connection limits.
  if (!mysqlPool) {
    mysqlPool = mysql.createPool(mysqlConfig);
  }
  mysqlPool.query('SELECT NOW() AS now', (err, results) => {
    if (err) {
      console.error(err);
      res.status(500).send(err);
    } else {
      res.send(JSON.stringify(results));
      console.log("Connected!")
    }
  });
  // Close any SQL resources that were declared inside this function.
  // Keep any declared in global scope (e.g. mysqlPool) for later reuse.
};

然后我尝试发布它以查看它是否有效,但出现错误:

模块 'mysql' 未在 package.json 中列为依赖项

所以我通过执行npm install mysql来安装mysql

我再次运行它,这次出现错误:

src/index.ts(23,15(: 错误 TS2339: 属性"socketPath"在类型"{ connectionLimit: number; user: string; password: string; database: string; }" 上不存在

这是怎么回事?我是否正确安装了它?我很迷茫,文档似乎没有提供太多解决方案。谢谢!

这似乎是一个 TypeScript 错误,其中正在推断配置对象的接口,然后您尝试在该对象上添加一个未声明的额外字段。换句话说,来自Google的示例代码是JavaScript,您正在使用TypeScript并遇到TS错误。

我认为您应该能够调整mysqlConfig声明以包含socketPath属性(设置为 null(,一切都应该没问题。换句话说,将mysqlConfig定义更改为:

const mysqlConfig = {
  connectionLimit: 1,
  user: dbUser,
  password: dbPassword,
  database: dbName,
  socketPath: null
};

相关内容

  • 没有找到相关文章

最新更新