gpt4 book ai didi

node.js - 在 Sails.js 中定义可重用函数的正确位置

转载 作者:搜寻专家 更新时间:2023-10-31 22:57:40 25 4
gpt4 key购买 nike

我有很多函数,比方说 P()、Q()、R()、S()、T(),我有 3 个 Controller ,A、B 和 C。

Controller A 使用 P() 和 Q(),B 使用 R()、S() 和 T(),而 C 使用 P()、Q() 和 T()。

我已经定义了 Controller ,我应该在哪里定义功能(哪个文件夹)?我如何将它们包含在 Controller 中?

这些功能以后可能会在其他一些 Controller 中使用(并且可以归类)。

最佳答案

在 Sails 1.0 中,您应该使用 Helpers而不是服务。

As of v1.0, all Sails apps come with built-in support for helpers, simple utilities that let you share Node.js code in more than one place. This helps you avoid repeating yourself, and makes development more efficient by reducing bugs and minimizing rewrites. Like actions2, this also makes it much easier to create documentation for your app.

您可以生成一个运行命令的新助手:

sails generate helper get-current-date

将在 helpers 文件夹下创建一个新文件。示例:

module.exports = {
friendlyName: 'Get current date',
description: 'Creates a new Date object and returns it',
inputs: {},
exits: {
success: {
outputFriendlyName: 'Current date',
outputType: 'ref'
},
},
fn: async function (inputs, exits) {
return exits.success(new Date());
}
};

然后像 sails.helpers.getCurrentDate() 一样使用它。

关于node.js - 在 Sails.js 中定义可重用函数的正确位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31668911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com