Skip to content

Commit

Permalink
actually
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Feb 16, 2022
1 parent 0b4ca77 commit e40043f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,12 @@

const base = 'https://api.svelte.dev';

export async function api(method: string, resource: string, data?: Record<string, unknown>) {
const res = await fetch(`${base}/${resource}`, {
export function api(method: string, resource: string, data?: Record<string, unknown>) {
return fetch(`${base}/${resource}`, {
method,
headers: {
'content-type': 'application/json'
},
body: data && JSON.stringify(data)
});

return {
status: res.status,
headers: res.headers,
body: await res.json()
};
}
22 changes: 12 additions & 10 deletions packages/create-svelte/templates/default/src/routes/todos/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { api } from './_api';
import type { RequestHandler } from '@sveltejs/kit';

export const get: RequestHandler = async ({ request, locals }) => {
export const get: RequestHandler = async ({ locals }) => {
// locals.userid comes from src/hooks.js
const response = await api('get', `todos/${locals.userid}`);

Expand All @@ -18,7 +18,7 @@ export const get: RequestHandler = async ({ request, locals }) => {
if (response.status === 200) {
return {
body: {
todos: response.body
todos: await response.json()
}
};
}
Expand All @@ -28,21 +28,23 @@ export const get: RequestHandler = async ({ request, locals }) => {
};
};

const redirect = {
status: 303,
headers: {
location: '/todos'
}
};

export const post: RequestHandler = async ({ request, locals }) => {
const form = await request.formData();

await api('post', `todos/${locals.userid}`, {
text: form.get('text')
});

return redirect;
return {};
};

// If the user has JavaScript disabled, the URL will change to
// include the method override unless we redirect back to /todos
const redirect = {
status: 303,
headers: {
location: '/todos'
}
};

export const patch: RequestHandler = async ({ request, locals }) => {
Expand Down

0 comments on commit e40043f

Please sign in to comment.