我這里有一個簡單的 Express API。當用戶提交鏈引數時,我想將引數轉換為物件。根據輸入,物件將具有不同的值現在我只有一堆 if 陳述句堆疊
是否有更好的實踐解決方案來實作這一點,因為這非常笨重?
app.get('/gettokens/:chain/:address', async(req, res) => {
const address = req.params.address;
let chain = req.params.chain;
if (chain == 'bsc') {
chain = {
moralis: 'bsc',
coingecko: 'binance-smart-chain'
}
}
if (chain == 'eth') {
chain = {
moralis: 'eth',
coingecko: 'ethereum'
}
}
if (chain == 'avax') {
chain = {
moralis: 'avalanche',
coingecko: 'avalanche'
}
}
if (chain == 'matic') {
chain = {
moralis: 'matic',
coingecko: 'polygon-pos'
}
}
uj5u.com熱心網友回復:
您可以嘗試使用常量物件
const chainDef = {
bsc: {
moralis: ‘bsc’,
coingecko: ‘binance-smart-chain’
} ,
…
}
// you should validate `req.params.chain` before doing this
const chain = chainDef[req.params.chain]
希望這可以幫助!
uj5u.com熱心網友回復:
您可以使用一些配置物件來處理它
像這樣
const config = {
bsc: {
moralis: 'bsc',
coingecko: 'binance-smart-chain'
},
eth: {
moralis: 'eth',
coingecko: 'ethereum'
},
avax: {
moralis: 'avalanche',
coingecko: 'avalanche'
},
matic: {
moralis: 'matic',
coingecko: 'polygon-pos'
}
}
const fallback = {
moralis: 'something',
coingecko: 'something'
}
const getChain = (key) => config[key] || fallback
console.log(getChain('matic'))
console.log(getChain('not defined'))
uj5u.com熱心網友回復:
您可以使用所有不同的值定義一個物件,并使用預期req.params.chain的作為鍵:
const ChainObjs = {
bsc: {
moralis: 'bsc',
coingecko: 'binance-smart-chain'
},
eth: {
moralis: 'eth',
coingecko: 'ethereum'
},
...
}
然后你可以像這樣得到正確的值
app.get('/gettokens/:chain/:address', async(req, res) => {
let chain = ChainObjs[req.params.chain]
})
uj5u.com熱心網友回復:
正如大衛建議的那樣,您可以使用switch 陳述句:
/*
app.get('/gettokens/:chain/:address', async(req, res) => {
const address = req.params.address;
let chain = splitChain(req.params.chain);
}
*/
function splitChain(value) {
let coingecko
switch (value) {
case 'bsc':
coingecko = 'binance-smart-chain'
break;
case 'eth':
coingecko = 'ethereum'
break;
case 'avax':
coingecko = 'avalanche'
break;
case 'matic':
coingecko = 'polygon-pos'
break;
default:
coingecko = null
break;
}
return {
moralis: value,
coingecko: coingecko
}
}
console.log(splitChain('bsc'))
console.log(splitChain('eth'))
console.log(splitChain('avax'))
console.log(splitChain('wrong-value'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/457436.html
標籤:javascript 节点.js 表示
