我是node的新手,现在我将其广泛地用于firebase功能。我发现了这段美妙的代码here:
const app = express();
const main = express();
main.use('/', app);
main.use(bodyParser.json());
main.use(bodyParser.urlencoded({
extended: false
}));
exports.webApi = functions.https.onRequest(main);
const glob = require("glob");
const files = glob.sync('./**/*.function.js', {
cwd: __dirname,
ignore: './node_modules/**'
});
for (let f = 0, fl = files.length; f < fl; f++) {
const file = files[f];
const functionName = file.split('/').pop().slice(0, -12); // Strip off '.function.js'
if (!process.env.FUNCTION_NAME || process.env.FUNCTION_NAME === functionName) {
exports[functionName] = require(file);
}
}
这梳理了functions / filename / etc.f.js中的文件堆栈,并提取了我所有以f.js结尾的导出函数。效果很好。现在,我将其重新定位为也尝试为api路由引入类似的文件堆栈,现在看起来像这样
const app = express();
const main = express();
main.use('/', app);
main.use(bodyParser.json());
main.use(bodyParser.urlencoded({
extended: false
}));
exports.webApi = functions.https.onRequest(main);
const glob = require("glob");
const camelCase = require("camelcase");
const files = glob.sync('./**/*.js', {
cwd: __dirname,
ignore: ['./node_modules/**', './index.js']
});
for (let f = 0, fl = files.length; f < fl; f++) {
const file = files[f];
const pathCheck = file.slice(-6, -3);
if (pathCheck === 'api') {
const path = file.slice(1, -7); // Strip off '.api.js'
app.use(`${path}`, require(file));
} else {
const functionName = camelCase(file.slice(0, -5).split('/').join('_')); // Strip off '.f.js'
if (!process.env.FUNCTION_NAME || process.env.FUNCTION_NAME === functionName) {
exports[functionName] = require(file);
}
}
}
我的api堆栈的文件结构如下
functions
---api
------v1
--------deposit.api.js
--------invoice.api.js
------v2
--------deposit.api.js
--------deposit
------------:depistId (file name)
-----------------transaction.api.js
---db
------deposit
------------onCreate.f.js
------------onUpdate.f.js
预期路径为
/api/v1/deposit
/api/v1/invoice
/api/v2/deposit
/api/v2/deposit/:deposit/transaction
在每个filename.api.js文件中,我都会受到一些影响
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now())
next()
});
router.delete('/:depositId', (req, res) => {
// firebaseHelper.firestore
// .deleteDocument(db, contactsCollection, req.params.contactId);
return res.status(200).send('Deposit deleted');
});
module.exports = router
它似乎不起作用。如果我手动添加路径并需要index.js中的文件,则可以正常工作。想知道我的代码是否有问题,或者对节点的工作原理有所了解,请提供帮助。
第一个问题,哇!
预先感谢
乍得