Skip to content

Commit

Permalink
package & sveltekit-zero-api preflight requests
Browse files Browse the repository at this point in the history
  • Loading branch information
kauderk committed Feb 24, 2023
1 parent 9cd24ad commit 603c600
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 11 deletions.
33 changes: 33 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
.DS_Store
node_modules
/build
/.svelte-kit
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

# Local Netlify folder
.netlify
dist

# npm
src
.netlify
.svelte-kit
.git
.vscode
patches
static
tests

.eslintignore
.eslintrc.cjs
.npmrc
.prettierignore
.prettierrc
*.config.*
tsconfig.json
netlify*
*-lock*
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
"private": true,
"scripts": {
"dev": "set NODE_OPTIONS=--inspect && vite dev",
"build": "rimraf dist && vite build",
"build": "rimraf dist && rimraf .netlify/!(state.json) && vite build",
"preview": "vite preview",
"check-netlify-deploy": "set CI=; && vite build && netlify deploy",
"check-netlify-deploy": "set CI=; && npm run build && netlify deploy",
"package": "vite build --config vite.config.package.ts --watch",
"test": "playwright test",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
Expand Down
25 changes: 25 additions & 0 deletions patches/sveltekit-zero-api@0.12.1.patch
Original file line number Diff line number Diff line change
@@ -1,3 +1,28 @@
diff --git a/api/handler.js b/api/handler.js
index 59fd529f8ca36f179d7602214d5a54298540ca53..5fc2f82d070fde38acac0bd69e5b1ba9f1a78f92 100644
--- a/api/handler.js
+++ b/api/handler.js
@@ -18,7 +18,7 @@ export default function handler(options, api) {
const stringifyQueryObjects = options.config.stringifyQueryObjects === undefined ? true : options.config.stringifyQueryObjects;
if (stringifyQueryObjects && 'query' in api)
stringifyQuery(api);
- const url = options.config.baseUrl || '' + options.path + ('query' in api ? '?' + new URLSearchParams(api.query).toString() : '');
+ const url = (options.config.baseUrl || '') + options.path + ('query' in api ? '?' + new URLSearchParams(api.query).toString() : '');
const baseData = options.config.baseData || {};
const isForm = Object.prototype.toString.call(api.body) === '[object FormData]';
if (!('content-type' in api.headers))
@@ -54,7 +54,10 @@ export default function handler(options, api) {
const requestInit = { ...baseData, ...api, headers: { ...(baseData['headers'] || {}), ...(api['headers'] || {}) } };
if (api.body === undefined)
delete requestInit['body'];
- const response = fetch(url, requestInit);
+ // avoid making the "preflight http request", which will make it twice as fast
+ const collapsedRequestInit = api.method === 'GET' ? undefined : requestInit
+
+ const response = fetch(url, collapsedRequestInit);
response.then(async (res) => {
const json = (res.headers.get('content-type') || '').includes('application/json') && await res[options.config.format || 'json']();
// TODO: Handle other responses than just JSON
diff --git a/api-types/api-updater.js b/api-types/api-updater.js
index 07a166114c41a789139058a6fbbe87689bb9c240..8533c1e333194494401b392bd99cad34dc6dc119 100644
--- a/api-types/api-updater.js
Expand Down
6 changes: 3 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 17 additions & 3 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,25 @@
import type { Handle } from '@sveltejs/kit'

const allowAnyOrigin = { 'Access-Control-Allow-Origin': '*' }
export const handle: Handle = async ({ event, resolve }) => {
if (event.request.method === 'GET') {
event.setHeaders({
'Access-Control-Allow-Origin': '*',
if (event.request.method === 'OPTIONS') {
// Respond to preflight requests
// I'm assuming that sveltekit internal fetch()/Requests
// comply with these headers
// but to allow sveltekit-zero-api's handler function to do it's job it must be explicit
return new Response(null, {
headers: {
...allowAnyOrigin,
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers':
'Content-Type, cache-control, x-requested-with',
},
})
}

if (event.request.method === 'GET') {
event.setHeaders(allowAnyOrigin)
}

return await resolve(event)
}
15 changes: 13 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
import Api from './api'
import { createZeroApi } from 'sveltekit-zero-api/api'
import type { GeneratedAPI } from './sveltekit-zero-api'

export default Api
const routes = createZeroApi({
baseUrl: 'https://youtube-browser-api.netlify.app',
onError: async err => console.error('[youtube-browser-api]', err),
prependCallbacks(method) {
method.Error(err => {
console.warn('Error', err)
})
},
}) as GeneratedAPI

export default routes
2 changes: 1 addition & 1 deletion vite.config.package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default defineConfig({
},
},
build: {
outDir: 'src/package',
outDir: 'package',
minify: false,
lib: {
entry: resolve(__dirname, 'src/index.ts'),
Expand Down

0 comments on commit 603c600

Please sign in to comment.