Skip to content

Commit

Permalink
feat: fetchOptions and headers
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon Erslev Milfred committed Jul 10, 2023
1 parent 6a91a88 commit 3d5a204
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 18 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@limbo-works/umbraco-get-data",
"version": "0.7.0",
"version": "0.8.0",
"license": "MIT",
"type": "module",
"exports": {
Expand Down
41 changes: 24 additions & 17 deletions src/runtime/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@ export default defineNuxtPlugin((nuxtApp) => {
// const NOT_FOUND_STATUS_CODE = 404
// const I_AM_A_TEAPOT_STATUS_CODE = 418
// const INTERNAL_SERVER_ERROR_STATUS_CODE = 500

const fetchData = async (config = {}) => {
const environment = useRuntimeConfig();

/**
* host handling start
*
*/
const headers = useRequestHeaders();
let appHost = '';

if (process.server) {
appHost = headers.host;
}
Expand All @@ -26,43 +26,50 @@ export default defineNuxtPlugin((nuxtApp) => {
const { hostname } = new URL(window.location.href);
appHost = hostname;
}

const isLocalHost =
appHost.includes('localhost') ||
/\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}/.test(appHost);

appHost = isLocalHost ? environment.public.appHost : appHost;

/**
* host handling end
*/

const urlSearchParams = new URLSearchParams({
appHost,
navContext: process.server,
navLevels: 2,
url: config.route,
...config.params
});

const data = await $fetch(
`/${UMBRACO_GET_DATA_ENDPOINT}?${urlSearchParams.toString()}`
`/${UMBRACO_GET_DATA_ENDPOINT}?${urlSearchParams.toString()}`,
{
...config?.fetchOptions || {},
headers: {
cookie: headers.cookie,
...config?.fetchOptions?.headers || {},
},
},
);

return data;
}
}

const processData = (data = {}) => {
if (data.meta?.code) {
// Overwrite the response code (does nothing client side)
setResponseStatus(data.meta.code);

// Special handlings
switch (data.meta.code) {
case 301:
if (nuxtApp.ssrContext) {
const { res } = nuxtApp.ssrContext;

if (data.meta.redirect) {
res.writeHead(301, {
Location: data.meta.redirect
Expand All @@ -73,15 +80,15 @@ export default defineNuxtPlugin((nuxtApp) => {
window.location.replace(data.meta.redirect);
}
break;

default:
break;
}
}

return data;
}

// Make an $umbracoClient object available with our methods
const umbracoClient = {
fetchData,
Expand Down

0 comments on commit 3d5a204

Please sign in to comment.