我有两个不同但相似的函数来进行api调用。 我想知道是否有办法咖喱他们?
const getNameMatches = async partialName=> {
const { data: documents} = await axios.get(
`api/Documents/SearchDocument?searchString=${partialName}`,
);
const { data: clients } = await axios.get('api/Clients/GetAll');
return documents.map(document=> ({
label: document.Name,
subLabel: clients.find(c => c.id === document.clientID)?.firstName,
value: document,
}));
const getAddressMatches = async partialAddress=> {
const { data: documents} = await axios.get(
`api/Documents/SearchDocumentByAddress?searchString=${partialAddress}`,
);
const { data: clients } = await axios.get('api/Clients/GetAll');
return documents.map(document=> ({
label: document.propertyAddress,
subLabel: clients.find(c => c.id === document.clientID)?.firstName,
value: document,
}));
我将两个功能组合为一个功能,但我想咖喱它们,想知道这是否可能。
组合功能:
const getMatches = async (state, partialString) => {
const tabValue = state.tabValue;
const { data } = await axios.get(
`api/Documents/SearchDocument${
tabValue === 'Address' ? 'ByAddress' : ''
}?searchString=${partialString}`,
);
const { data: clients } = await axios.get('api/Clients/GetAll');
return data.map(loan => ({
label: tabValue === 'Name' ? document.name: document.propertyAddress,
subLabel: clients.find(c => c.id === loan.clientID)?.firstName,
value: document,
}));
};
答案 0 :(得分:1)
唯一的区别是API URL和标签。
因此您可以收集它们并使其通用化
const getMatches = async (partialValue,type)=> {
let urlString="",label="";
if(type==='name'){
urlString="SearchDocument";
label="Name";
}else{
urlString="SearchDocumentByAddress";
label="propertyAddress";
}
const { data: documents} = await axios.get(
`api/Documents/${urlString}?searchString=${partialValue}`,
);
const { data: clients } = await axios.get('api/Clients/GetAll');
return documents.map(document=> ({
label: document[label],
subLabel: clients.find(c => c.id === document.clientID)?.firstName,
value: document,
}));
答案 1 :(得分:0)
如果您确实想要currying,则可以执行以下操作:
const searchFor = type => {
const path = type === 'name'
? 'SearchDocument'
: 'SearchDocumentByAddress';
const prop = type === 'name'
? 'Name'
: 'propertyAddress';
return function(string){
const apiDocs = `api/Documents/${path}?searchString=${string}`;
const apiClients = `api/Clients/GetAll`;
const documents = await axios.get(apiDocs);
const clients = await axios.get(apiClients);
return documents.map(document => ({
label: document[prop],
subLabel: clients.find(c => c.id === document.clientID).firstName,
value: document
}));
}
}
然后您可以这样称呼它:
const getNameMatches = searchFor('name');
getNameMatches('foobar');
/* OR */
const getAddrMatches = searchFor('address');
getAddrMatches('foobar');