首页 > 解决方案 > GCP 云功能中的文件拆分不起作用

问题描述

我目前正在使用 GCP 云功能构建无服务器应用程序。

为了为每个功能单独部署云功能,我将模块拆分如下。

当我在 index.ts 中编写所有函数时,它在本地可以正常工作,但是当我导出它时,我无法运行它并出现以下错误。

'getUsers' needs to be of type function. Got: object

导出方法有问题吗?

这是在本地运行它的命令

"start": "npm run build && functions-framework --source=build/src/ --target=getUsers",

索引.ts

import * as express from 'express';
import * as getUsers from '@src/cloudFunctions/userFunctions';
import * as getUserById from '@src/cloudFunctions/userFunctions';
import * as updateUserById from '@src/cloudFunctions/userFunctions';
import * as deleteUserById from '@src/cloudFunctions/userFunctions';

export {
  getUsers,
  getUserById,
  updateUserById,
  deleteUserById,
};

用户函数.ts

import * as express from 'express';

const app = express();
    
exports.getUsers = app.get('/users',
  ///logic goes here
);

exports.getUserById = app.get('/users/:id',
  ///logic goes here
);

exports.updateUserById = app.put('/users/:id',
  ///logic goes here
);

exports.deleteUserById = app.delete('/users/:id',
  ///logic goes here
);

标签: google-cloud-platformgoogle-cloud-functions

解决方案


我将 userFunctions.ts 拆分为每个函数的单独文件,并按如下方式更改了 index.ts,并且它起作用了。

我想我使用了错误的导出方法。

//userFunctions
const getUsers = require('@src/cloudFunctions/users/getUsers');
const getUserById = require('@src/cloudFunctions/users/getUserById');
const updateUserById = require('@src/cloudFunctions/users/updateUserById');
const deleteUserById = require('@src/cloudFunctions/users/deleteUserById');
const getUserSellingItems = require('@src/cloudFunctions/users/getUserSellingItems');
const getUserLatestSellingItems = require('@src/cloudFunctions/users/getUserLatestSellingItems');
const getUserCollectedItems = require('@src/cloudFunctions/users/getUserCollectedItems');

//userFunctions
exports.getUsers = getUsers.getUsers;
exports.getUserById = getUserById.getUserById;
exports.updateUserById = updateUserById.updateUserById;
exports.deleteUserById = deleteUserById.deleteUserById;

推荐阅读