1.0.9 • Published 3 years ago

skapi v1.0.9

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

Svapi - SvelteKit API Helper

Svapi makes SvelteKit API development simpler by providing a sort of pseudo-middleware to handle things like token authentication and error/data responses.

What it does

You pass in the standard SvelteKit request object, and returns a req (which is the same as the original request but with some added stuff) and a res which helps with formatting the JSON response in a DRY and consistent way.

Example POST with plain SvelteKit and Mongoose

// POST /books
export async function post(request) {
  let error;
  const book = await Book.create(request.body).catch(err => error = err);
  if (error) {
    return {
      status: 400,
      body: {
        error: error
      }
    }
  }
  if (book) {
  	return {
      status: 200,
      body: {
        data: book
      }
    }  
  }
}

Now here's the same thing using Svapi.

// POST /books
export async function post(request) {
  const {req, res} = svapi(request);
  const company = await Company.create(req.body).catch(err => res.setError(err));
  return res.send(company);
}

Wait. What just happened?

We always start by passing the request object to svapi() which returns req, and res objects.

req

The req object has all the attributes of the original SvelteKit request object (so stuff like body and params, etc. will all be there) – but then Svapi adds a couple other juicy nuggets as well. For example, if a JWT was included in the headers, it will automatically be validated, decoded and available at req.token. More about that later.

res

The res object provides a few handy methods for formatting your response. To return a success response containing data, just return res.send(myData) – which is identical to:

return {
	status: 200,
	body: {
		status: 200
		data: myData
	}
}

(but saves a lot of typing).

You also may have noticed the catch block passes the err object into res.setError(). This saves the error to the res object so the last line will return that error instead of the data. The res.send() call gets hijacked if you've previously called res.setError().

1.0.9

3 years ago

1.0.8

3 years ago

1.0.6

3 years ago

1.0.7

3 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

3 years ago