2016-12-04 46 views
1

我正在寫一個ES6模塊,但豪不知道如何從我的主要index.js省略的說法,但還是簽在我的公開方法。傳遞參數給ES6模塊作爲可選

// index.js 
import {getStatus, openingHours} from './lib/methods.js'; 

export default ID => { 
    if(!ID) throw new Error(`An ID needs to be passed`); 

    return { 
    getStatus: getStatus(ID), 
    openingHours: openingHours(ID), 
    }; 
}; 


// lib/methods.js 
import find from 'lodash.find'; 
import composedFetch from '../composedFetch.js'; 

export const getStatus = id => composedFetch(id) 
    .then(data => find(data.processOverview.processSteps, { status: `active` })) 
    .catch(e => console.log(e)); 

export const openingHours = (id, day) => { 
    if (!day) throw new Error(`Please specify a day`); 

    return composedFetch(id) 
    .then(data => { 
     const obj = find(
     data.deliveryPoint.openingSchedules, 
     { dayOfTheWeek: day.toUpperCase() } 
    ); 

     return obj.openingHours[0]; 
    }) 
    .catch(e => console.error(e)); 
}; 

正如你可以看到我的方法需要一個參數的一天。該模塊應該工作的方式是讓你先用一個ID實例,然後使用方法:

import bpost from 'bpost'; 

const pkg = bpost('someIDhere'); 
const status = pkg.getStatus(); 
const openingHours = pkg.openingHours('monday'); 

我試着與其他運營商和默認參數,但沒有運氣這樣做呢。我的測試仍然給這個測試代碼拋出一天的錯誤(這應該一旦這個問題解決):

// methods.test.js 
import bpost from '../src/index.js'; 

describe(`Method: global.bpost`,() => { 
    it(`should show the available methods for the module`,() => { 
    expect(() => bpost(`someIDhere`)).not.toThrow(); 
    }); 
}); 

在此先感謝!

+0

我最初雖然會改變,如果條件做不同的基礎上它,而那個扔東西的錯誤(天!) - 因爲在你的情況下,您仍想使用,即使沒有指定一天這個功能。可能是某種門面會給明確的結果,看看這個簡單的想法:http://www.dofactory.com/javascript/facade-design-pattern – eloleon

+0

@eloleon HMM可能有console.error改變它,而不是,但我如果一天不通過,不希望函數執行。 – thibmaek

+0

我認爲你正在尋找這個http://stackoverflow.com/questions/36314/what-is-currying – duivvv

回答

1

你需要做的

export default ID => { 
    if(!ID) throw new Error(`An ID needs to be passed`); 

    return { 
    getStatus:() => getStatus(ID), 
    openingHours: day => openingHours(ID, day), 
    }; 
}; 

,使返回的對象的屬性實際上是方法。

另外,

return { 
    getStatus: getStatus.bind(null, ID), 
    openingHours: openingHours.bind(null, ID), 
    }; 

會做相同的,但更容易推廣(比如,如果你想自動裝飾全部採用進口方式)。

+0

感謝使用第一個片段,我可以以最好的方式解決它;) – thibmaek