'use strict'

const request = require('request-promise')

module.exports = function (context, input) {
  const headers = {
    'x-functions-key': process.env.AZURE_FUNCTIONS_KEY
  }

  const json = true

  context.log('Requesting list of PokeAPI endpoints...')

  request({
    uri: 'https://pierluc-io.azurewebsites.net/api/pokeapi-endpoints', headers, json
  }).then((body) => {
    context.log(`Requesting resource list for ${body.results.length} endpoints...`)

    return Promise.all(body.results.map((endpoint) => request({
      uri: 'https://pierluc-io.azurewebsites.net/api/pokeapi-resource-list', headers, json,
      qs: {
        endpoint: endpoint.name
      }
    })))
  }).then((data) => {
    const resourceList = []

    context.log(`Aggregating resource lists from ${data.length} endpoints...`)

    data.map((resources) => resources.map((resource) => resource.results.map((result) => {
      resourceList.push(Object.assign(result, {
        endpoint: resource.endpoint
      }))
    })))

    return Promise.resolve(resourceList)
  }).then((resources) => {
    context.log(`Aggregated ${resources.length} resource lists!`)

    return resources.reduce((promise, resource, i, resources) => {
      context.log(`Requesting ${resource.endpoint} ${resource.id || resource.name} (${i + 1} / ${resources.length})`)

      return request({
        uri: 'https://pierluc-io.azurewebsites.net/api/pokeapi-resource', headers, json,
        qs: {
          endpoint: resource.endpoint,
          id: resource.id || resource.name
        }
      }).then((body) => {
        context.log(`Upserting ${resource.endpoint} ${resource.id || resource.name} (${i + 1} / ${resources.length})`)

        return request({
          uri: 'https://pierluc-io.azurewebsites.net/api/pokedex-upsert', headers, json,
          method: 'POST',
          qs: {
            endpoint: resource.endpoint
          },
          data: body
        })
      })
    }, Promise.resolve())
  }).then(() => {

  }).catch((err) => {
    context.log(`An error occured: ${err.stack}`)
  })
}

@@ -716,20 +716,17 @@
 resource
-List
+s
  = %5B%5D%0A%0A 
@@ -761,21 +761,16 @@
 resource
- list
 s from $
@@ -775,39 +775,35 @@
  $%7Bdata.length%7D 
-endpoin
+lis
 ts...%60)%0A%0A    dat
@@ -808,40 +808,15 @@
 ata.
-map((resources) =%3E resources.map
+forEach
 ((re
@@ -843,19 +843,23 @@
 results.
-map
+forEach
 ((result
@@ -862,24 +862,16 @@
 sult) =%3E
- %7B%0A     
  resourc
@@ -871,20 +871,17 @@
 resource
-List
+s
 .push(Ob
@@ -900,34 +900,32 @@
 result, %7B%0A      
-  
 endpoint: resour
@@ -940,24 +940,15 @@
 int%0A
-  
     %7D))
-%0A    %7D)
 ))%0A%0A
@@ -986,12 +986,9 @@
 urce
-List
+s
 )%0A  
@@ -1068,21 +1068,16 @@
 resource
- list
 s!%60)%0A%0A  
@@ -1918,16 +1918,60 @@
 () =%3E %7B%0A
+    context.log('Done!')%0A%0A    context.done()
 %0A  %7D).ca

Fix logic