Skip to content

Commit

Permalink
Merge pull request #2 from limbo-works/1-Feature-Add-support-for-cust…
Browse files Browse the repository at this point in the history
…om-`dataEndpointUrl`

[RFC][NU-1] Feature: Added support for custom `getdataEndpointUrl`
  • Loading branch information
AskeLange authored Mar 22, 2023
2 parents e05c4cc + 6246c9e commit 97be985
Show file tree
Hide file tree
Showing 9 changed files with 366 additions and 344 deletions.
10 changes: 0 additions & 10 deletions .eslintrc

This file was deleted.

14 changes: 14 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module.exports = {
"extends": [
"@nuxtjs/eslint-config-typescript"
],
"rules": {
"indent": ['error', 'tab'],
"quotes": ['error', 'single'],
"semi": ['error', 'always'],
'prefer-destructuring': ['warn', { object: true, array: false }],
'no-unused-vars': ['warn'],
'no-undef': 0,
"@typescript-eslint/no-unused-vars": ["off"]
}
}
7 changes: 7 additions & 0 deletions .prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
trailingComma: 'es5',
tabWidth: 4,
useTabs: true,
semi: true,
singleQuote: true,
};
12 changes: 11 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1 +1,11 @@
{}
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"editor.detectIndentation": false,
"editor.insertSpaces": false,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"files.eol": "\r\n",
"tailwindCSS.emmetCompletions": true
}
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/nuxt-umbraco",
"version": "0.4.4",
"version": "0.5.0",
"license": "MIT",
"type": "module",
"exports": {
Expand Down
72 changes: 42 additions & 30 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,45 @@
import { resolve } from 'path'
import { fileURLToPath } from 'url'
import { defineNuxtModule, addPlugin, createResolver, addServerHandler } from '@nuxt/kit'
import { fileURLToPath } from 'url';

import {
defineNuxtModule,
addPlugin,
createResolver,
addServerHandler
} from '@nuxt/kit';
export interface ModuleOptions {
addPlugin: boolean
addApiProxy: boolean
}
addPlugin: boolean;
addApiProxy: boolean;
};

export default defineNuxtModule<ModuleOptions>({
meta: {
name: 'my-module',
configKey: 'myModule'
},
defaults: {
addPlugin: true,
addApiProxy: true
},
setup (options, nuxt) {
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
if (options.addPlugin) {
const { resolve } = createResolver(import.meta.url)
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
nuxt.options.build.transpile.push(runtimeDir)
addPlugin(resolve(runtimeDir, 'plugin'))
}
if (options.addApiProxy) {
addServerHandler({
route: '/api/data',
handler: resolve(runtimeDir, 'server/api/data')
})
}
}
})
meta: {
name: 'nuxt-umbraco',
configKey: 'NuxtUmbraco',
compatibility: {
nuxt: '^3.0.0'
}
},

defaults: {
addPlugin: true,
addApiProxy: true,
},

setup (options, nuxt) {
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url));
const { resolve } = createResolver(import.meta.url);
console.log(resolve(runtimeDir, 'server/api/data'));

if (options.addPlugin) {
nuxt.options.build.transpile.push(runtimeDir);
addPlugin(resolve(runtimeDir, 'plugin'));
}

if (options.addApiProxy) {
addServerHandler({
route: '/api/data',
handler: resolve(runtimeDir, 'server/api/data')
});
}
}
});
179 changes: 91 additions & 88 deletions src/runtime/plugin.js
Original file line number Diff line number Diff line change
@@ -1,93 +1,96 @@
import { defineNuxtPlugin, useRuntimeConfig, useRequestHeaders, setResponseStatus } from '#app'

export default defineNuxtPlugin((nuxtApp) => {
const UMBRACO_GET_DATA_ENDPOINT = 'api/data'
const REDIRECT_STATUS_CODES = [301, 302, 307, 308]
const BAD_REQUEST_STATUS_CODE = 400
const NOT_FOUND_STATUS_CODE = 404
const I_AM_A_TEAPOT_STATUS_CODE = 418
const INTERNAL_SERVER_ERROR_STATUS_CODE = 500
const UMBRACO_GET_DATA_ENDPOINT = 'api/data';
// const REDIRECT_STATUS_CODES = [301, 302, 307, 308]
// const BAD_REQUEST_STATUS_CODE = 400
// 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;
}

const fetchData = async (config = {}) => {
const environment = useRuntimeConfig()
if (process.client) {
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()}`
);

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
});
res.end();
}
} else if (data.meta.redirect) {
window.location.replace(data.meta.redirect);
}
break;

default:
break;
}
}

return data;
}

// Make an $umbracoClient object available with our methods
const umbracoClient = {
fetchData,
processData
};

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

if (process.server) {
appHost = headers.host
}
if (process.client) {
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()}`
)

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
})
res.end()
}
} else if (data.meta.redirect) {
window.location.replace(data.meta.redirect)
}
break

default:
break
}
}

return data
}

// Make an $umbracoClient object available with our methods
const umbracoClient = {
fetchData,
processData
}
return {
provide: {
umbracoClient
}
}
})
return {
provide: {
umbracoClient
}
};
});
29 changes: 13 additions & 16 deletions src/runtime/server/api/data.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
import { sendProxy, defineEventHandler } from 'h3'
import { useRuntimeConfig } from '#nitro'
const config = useRuntimeConfig()
import { sendProxy, defineEventHandler } from 'h3';
import { useRuntimeConfig } from '#nitro';
const config = useRuntimeConfig();

export default defineEventHandler(async (event) => {
const target = new URL(
event.node.req.url.replace(/^\/api\/data/, '/umbraco/api/spa/getdata/'),
config.public.apiDomain
)
const headers = {
'X-Api-Key': config.apiKey
}
const data = await sendProxy(event, target.toString(), {
headers,
sendStream: false
})
return data
})
const target = new URL(
event.node.req.url.replace(/^\/api\/data/, config.getdataEndpointUrl || '/umbraco/api/spa/getdata/'),
config.public.apiDomain
);

const headers = { 'X-Api-Key': config.apiKey };
const data = await sendProxy(event, target.toString(), { headers, sendStream: false });
return data;
});

Loading

0 comments on commit 97be985

Please sign in to comment.