Home
Support Forums

Function only partially executed - doesn't fetch

Hi

I’ve written my first lambda function for Netlify. When im running the function locally with “netlify dev” everything works as expected. When running live, the fetch-function doesn’t run and doesn’t log anything error-wise. Only thing it logs is the data it receives (event.body)

My (reduced) code looks like this:

const fetch = require('node-fetch')
require('dotenv').config()

const TOKEN = process.env.TRELLO_TOKEN
const KEY = process.env.TRELLO_KEY
const CARD_ID = '614dc1e1de34b22264c2dfe9'

exports.handler = async (event, context) => {

  const getCustomFields = (event) => {
    console.log('Event.body:', JSON.parse(event.body))
    
    // Get all CustomFields of a specific card
    fetch(`https://api.trello.com/1/cards/${CARD_ID}/customFieldItems?key=${KEY}&token=${TOKEN}`, {
      method: 'GET',
      headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, 
    })
    .then(response => {
      console.log(`Response: ${response.status} ${response.statusText}`)
    })
    .catch(err => console.error('error of GET request', err))
  } 
  getCustomFields(event)

  return {
    statusCode: 200,
    body: JSON.stringify({ message: "Worked" })
  };
};

Think its very strange since it works well locally and I can’t think of anything why it shouldn’t start the fetch-function.

Any help very appreciated!

You need to change it to:

return fetch(`https://api.trello.com/1/cards/${CARD_ID}/customFieldItems?key=${KEY}&token=${TOKEN}`, {
      method: 'GET',
      headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, 
    })
...

Also, the function should be async but unless you need to call getCustomFields multiple times, I’d avoid using a function entirely. In that case, the code could be:

const fetch = require('node-fetch')

exports.handler = async () => {
  const TOKEN = process.env.TRELLO_TOKEN
  const KEY = process.env.TRELLO_KEY
  const CARD_ID = '614dc1e1de34b22264c2dfe9'
  return fetch(`https://api.trello.com/1/cards/${CARD_ID}/customFieldItems?key=${KEY}&token=${TOKEN}`, {
    method: 'GET',
    headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
  }).then(response => {
    console.log(`Response: ${response.status} ${response.statusText}`)
    return {
      statusCode: 200,
      body: JSON.stringify({ message: "Worked" })
    }
  }).catch(err => {
    console.error('error of GET request', err)
  })
}

You don’t need dotenv if you’re keeping the environment variables inside Netlify UI (you should do it this way).

Also, it’s better to keep all the secrets inside the exports.handler function.

Finally, if you have to write a helper function for the above thing, it would be like:

const fetch = require('node-fetch')

exports.handler = async event => {
  const TOKEN = process.env.TRELLO_TOKEN
  const KEY = process.env.TRELLO_KEY
  const CARD_ID = '614dc1e1de34b22264c2dfe9'
  async function getCustomFields(event) {
    return new Promise((resolve, reject) => {
      fetch(`https://api.trello.com/1/cards/${CARD_ID}/customFieldItems?key=${KEY}&token=${TOKEN}`, {
        method: 'GET',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
      }).then(response => {
        if (response.ok) {
          return response.json()
        } else {
          throw response.statusText
        }
      }).then(data => {
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  }
  return getCustomFields(event).then(() => {
    return {
      statusCode: 200,
      body: JSON.stringify({ message: "Worked" })
    }
  }).catch(error => {
    return {
      statusCode: 500,
      body: JSON.stringify({error: error})
    }
  })
}

NOTE: In this one, I’ve added response.json(), because most fetch requests need it, if yours doesn’t, you can skip that .then() block.