Svelte/Sapper How to fetch data from internal api without giving absolute URL
Asked Answered
G

1

5

I am using svelte/sapper with express.

I have an api in routes/billing/index.js

It needs to fetch data from customers/[customernumber]/detections.js

My question is how to fetch data from internal apis with in the routes folder using relative URLs

async function getDataFromGateway(customerNumber) {
  if (typeof fetch !== 'function') {
    global.fetch = require('node-fetch')
  }
  const data = await fetch(`http://localhost:19052/customers/${customerNumber}/detections`)
    .then(res => res.json())
    .catch(error => {
      console.log(error)
      return error
    }
    )
  return data
}

Is there a way to do this using relative url

Golter answered 7/2, 2020 at 17:39 Comment(0)
B
8

The easiest way is to fetch this data inside preload, using this.fetch, since that will automatically handle relative URLs the same way whether it's running on server or client:

<script context="module">
  export async function preload(page, session) {
    const r = await this.fetch(`customers/${getCustomerNumber(session)}/detections`);
    const data = await r.json();

    return {
      foo: data.foo
    };
  }
</script>

If that's not possible for whatever reason, you might need to configure an environment variable, e.g. BASE_URL:

async function getDataFromGateway(customerNumber) {
  if (typeof fetch !== 'function') {
    global.fetch = require('node-fetch')
  }
  const data = await fetch(`${process.env.BASE_URL}/customers/${customerNumber}/detections`)
    .then(res => res.json())
    .catch(error => {
      console.log(error)
      return error
    }
    )
  return data
}
Broaden answered 7/2, 2020 at 20:1 Comment(4)
Thanks Harris. Appreciate your time. But is there a way we can use this.fetch outside <script context="module">, in a javaScript fileGolter
No, because it's contextual — it resolves URLs relative to the route that's being preparedBroaden
Been discussing this in sapper discord channel. Isn't making an http request a bit of an unnecessary overhead and inefficient / slow? What about calling into the same code that /customers/${customerNumber}/detections triggers if you know you are on the server, and do the fetch if you know you are on the client?Besetting
I'll be writing an RFC soon that addresses this very topicBroaden

© 2022 - 2024 — McMap. All rights reserved.