Reputation: 353
I have written an API endpoint with the following code in Svelte that should help with getting a number of objects from a Prisma.io ORM based database.
The API endpoint is located at routes/api/[slug].json.ts
and contains a get function:
export async function get({ params }) {
const { slug } = params
const objects = await prisma[slug].findMany({})
objects.forEach(function (object, index: number) {
object.objectId = index
})
return objects
}
My view functionality is located in a Svelte file, called Cardview.svelte
. It contains the following code:
<script lang="ts">
export let object_model: string;
let title = toTitleCase(object_model);
async function obtain_objects(object_model: string) {
const url = 'http://localhost:3000/api/' + object_model + '.json';
const objects = await fetch(url);
return objects;
}
let objects = obtain_objects('measurement');
</script>
{#await objects}
Reading from server... <Spinner size="sm" type="grow" />
{:then objects}
<Container>
{#each objects as v}
<div class="shadow mb-5 bg-white rounded">
<Varcard variable={v} />
</div>
{/each}
</Container>
{:catch error}
There was an error in loading the JSON {object_model}.
<div><span>{error.message}</span></div>
{/await}
Some layout imports from other files were omitted.
The problem with this code is that the let objects = ..
part is never evaluated by the {#await...
syntax. This means, the page is always stuck in loading phase and the Javascript-object objects
always stays inside a promise. Where is the problem in my code?
Thanks.
Upvotes: 0
Views: 762
Reputation: 1234
Your get function is not returning correctly. You need to return your data in the 'body' attribute of your return:
return {
body: objects
}
Using fetch also requires an extra step:
async function obtain_objects(object_model: string) {
const url = 'http://localhost:3000/api/' + object_model + '.json';
const objects = await fetch(url);
return objects.json();
}
There are examples of the fetch api here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Upvotes: 1