Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throwable responses from endpoints #4712

Closed
wants to merge 1 commit into from
Closed

Throwable responses from endpoints #4712

wants to merge 1 commit into from

Conversation

coryvirok
Copy link
Contributor

The idea here is that endpoints can not only return a response, but also throw one.

E.g.

  // return a response from an endpoint
  export async function get() {
    return { status: 200, body: {} }
  }

  // throw a response from an endpoint
  export async function get() {
    throw { status: 401 }
  }

This is useful for building request validation libraries. E.g. to build an auth guard
for an endpoint without this change, you would need something like:

  export async function get() {
    if (!isAuthenticated()) {
      return { status: 401 }
    }
  }

And with this change, you can do:

  export async function get() {
    // Throws a 401 if the request is not authenticated
    verifyAuthenticated()
  }

This is a common pattern in other web frameworks and makes it easier to structure
your code.

Please don't delete this checklist! Before submitting the PR, please make sure you do the following:

  • It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
  • This message body should clearly illustrate what problems it solves.
  • Ideally, include a test that fails without this PR but passes with it.

Tests

  • Run the tests with pnpm test and lint the project with pnpm lint and pnpm check

Changesets

  • If your PR makes a change that should be noted in one or more packages' changelogs, generate a changeset by running pnpx changeset and following the prompts. All changesets should be patch until SvelteKit 1.0

The idea here is that endpoints can not only return a response, but also throw one.

E.g.

```js
  // return a response from an endpoint
  export async function get() {
    return { status: 200, body: {} }
  }

  // throw a response from an endpoint
  export async function get() {
    throw { status: 401 }
  }
```

This is useful for building request validation libraries. E.g. to build an auth guard
for an endpoint without this change, you would need something like:

```js
  export async function get() {
    if (!isAuthenticated()) {
      return { status: 401 }
    }
  }
```

And with this change, you can do:

```js
  export async function get() {
    // Throws a 401 if the request is not authenticated
    verifyAuthenticated()
  }
```

This is a common pattern in other web frameworks and makes it easier to structure
your code.
@changeset-bot
Copy link

changeset-bot bot commented Apr 23, 2022

⚠️ No Changeset found

Latest commit: 8ef184f

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@Rich-Harris
Copy link
Member

Thanks for the PR. We discussed this a bit in the maintainer's discord and decided against merging this, on the grounds that throw isn't a control flow mechanism — the endpoint with isAuthenticated() is much more understandable than the one with verifyAuthenticated(). It also makes things more complicated — https://kit.svelte.dev/docs/hooks#handleerror would need to change:

If an error is thrown during rendering, this function will be called with the error and the event that caused it, unless the error has a numeric status property, in which case it will be treated as an expected error rather than an unexpected one. This allows you to send data to an error tracking service, or to customise the formatting before printing the error to the console.

The modest convenience doesn't outweigh the potential for confusion.

A better solution might be to add a helper function like this:

// src/lib/authed.js
export function authed(fn) {
  return event => {
    if (!event.session.user) {
      return { status: 401 };
    }

    return fn ? fn(event) : {};
  }
}
// src/routes/whatever.js
import { authed } from '$lib/authed';

export const get = authed(); // guard without doing any actual work in the endpoint

export const get = authed(async event => {
  // in here, we know that `event.session.user` is populated
  return {...};
});

@coryvirok
Copy link
Contributor Author

Alright. Thanks for the consideration and response. I'll go with the pattern you described or possibly use middleware/endpoint layouts when they're available.

@coryvirok
Copy link
Contributor Author

For my own reference, the pattern I suggested here was essentially implemented via the error helper - https://kit.svelte.dev/docs/errors#expected-errors

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants