Export function using third party package

Asked

Viewed 32 times

1

I have a code snippet that I use to consume a API and use this same chunk 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 the package instance returns woocommerceAPI it should contain the function get, being 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.

1 answer

1


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

When you have module.exports = () => {...} this exports () => {...}, what you want to have is module.exports = new woocommerceAPI(...); 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.