Export function using third-party package

1

I have a piece of code that I use to consume a API and I use this same snippet in several files. So I created a module to export such a configuration:

'use strict'

// Module to access woocommerce API endpoints
var woocommerceAPI = require('woocommerce-api')

// Load the environment configuration
require('dotenv').config()

module.exports = () => {
  return new woocommerceAPI({
    url: process.env.URL,
    consumerKey: process.env.CONSUMERKEY,
    consumerSecret: process.env.CONSUMERSECRET,
    version: process.env.VERSION
  })

}

When returning the instance of package woocommerceAPI it should contain the get function, as follows.

const wc = require('./wc-config')

wc.get('products', (err, data, res) => {
  console.log(res)
})

But I only get the message that wc.get is not a function.

    
asked by anonymous 24.04.2017 / 23:11

1 answer

1

Notice that your file / module is exporting a function and not an instance of woocommerceAPI .

When you have module.exports = () => {...} it exports () => {...} , what you want to have is module.exports = new woocommerceAPI(...); to Singleton style.

So the code should be:

'use strict'

// Module to access woocommerce API endpoints
const woocommerceAPI = require('woocommerce-api')

// Load the environment configuration
require('dotenv').config()

const WooAPI = new woocommerceAPI({
    url: process.env.URL,
    consumerKey: process.env.CONSUMERKEY,
    consumerSecret: process.env.CONSUMERSECRET,
    version: process.env.VERSION
})
module.exports = WooAPI
    
25.04.2017 / 05:27