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

feat: Issue #3336148: Add support for forms #247

Merged
merged 10 commits into from
Aug 28, 2024
18 changes: 18 additions & 0 deletions playground/components/global/DrupalForm.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<template>
<form vue-enabled :formId="formId" :method="method" v-bind="attributes" :action="target">
fago marked this conversation as resolved.
Show resolved Hide resolved
<slot><div v-html="content" /></slot>
<input type="hidden" name="target_url" :value="target">
</form>
</template>

<script setup lang="ts">
const props = defineProps<{
formId: String,
attributes: Object,
method: String,
content?: String,
}>()

const match = props.content ? props.content.match(/action="([^"]*)"/) : null
fago marked this conversation as resolved.
Show resolved Hide resolved
const target = match ? match[1] : useRoute().path
</script>
16 changes: 0 additions & 16 deletions playground/middleware/redirect.global.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export default defineNuxtModule<ModuleOptions>({
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'))
addPlugin(resolve(runtimeDir, 'plugins/formHandler'))
if (options.serverLogLevel) {
addServerPlugin(resolve(runtimeDir, 'server/plugins/errorLogger'))
}
Expand Down
31 changes: 24 additions & 7 deletions src/runtime/composables/useDrupalCe/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { appendResponseHeader } from 'h3'
import type { UseFetchOptions } from '#app'
import type { $Fetch, NitroFetchRequest } from 'nitropack'
import { getDrupalBaseUrl, getMenuBaseUrl } from './server'
import { useRuntimeConfig, useState, useFetch, navigateTo, createError, h, resolveComponent, setResponseStatus, useNuxtApp, useRequestHeaders, ref, watch } from '#imports'
import { useRuntimeConfig, useState, useFetch, navigateTo, createError, h, resolveComponent, setResponseStatus, useNuxtApp, useRequestHeaders, ref, watch, useRequestEvent } from '#imports'

export const useDrupalCe = () => {
const config = useRuntimeConfig().public.drupalCe
Expand Down Expand Up @@ -116,9 +116,28 @@ export const useDrupalCe = () => {
page_layout: 'default',
title: '',
}))
const serverResponse = useState('server-response', () => null)
useFetchOptions.key = `page-${path}`
const page = ref(null)
const pageError = ref(null)

const { data: page, error } = await useCeApi(path, useFetchOptions, true)
if (import.meta.server) {
serverResponse.value = useRequestEvent(nuxtApp).context.nitro.response
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering whether we need to have the separate serverResponse state really. Let's try whether it works without as well. It seems we could directly set page.value / pageError here, not?
page should be already in a state, so it should be correctly hydrated on client-side with that state then, no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is needed to share the server data to the client, its not being hydrated

to make this better I added a line so it's cleared after its used

}

// Check if the page data is already provided, e.g. by a form response.
if (serverResponse.value && serverResponse.value._data) {
page.value = serverResponse.value._data
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this never sets pageErrror like the other if part. does it actually handle error codes correctly?

passThroughHeaders(nuxtApp, serverResponse.value.headers)
} else {
const { data, error } = await useCeApi(path, useFetchOptions, true)
page.value = data.value
pageError.value = error.value
}

if (page.value?.messages) {
pushMessagesToState(page.value.messages)
}

if (page?.value?.redirect) {
await callWithNuxt(nuxtApp, navigateTo, [
Expand All @@ -128,13 +147,11 @@ export const useDrupalCe = () => {
return pageState
}

if (error.value) {
overrideErrorHandler ? overrideErrorHandler(error) : pageErrorHandler(error, { config, nuxtApp })
page.value = error.value?.data
if (pageError.value) {
overrideErrorHandler ? overrideErrorHandler(pageError) : pageErrorHandler(pageError, { config, nuxtApp })
page.value = pageError.value?.data
}

page.value?.messages && pushMessagesToState(page.value.messages)

pageState.value = page
return page
}
Expand Down
4 changes: 0 additions & 4 deletions src/runtime/plugin.ts

This file was deleted.

37 changes: 37 additions & 0 deletions src/runtime/plugins/formHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { readFormData } from 'h3'
import { getDrupalBaseUrl } from '../composables/useDrupalCe/server.js'
import { defineNuxtPlugin, addRouteMiddleware, useRuntimeConfig, useRequestEvent } from '#imports'

export default defineNuxtPlugin(() => {
const runtimeConfig = useRuntimeConfig()
const { ceApiEndpoint } = runtimeConfig.public.drupalCe
const drupalBaseUrl = getDrupalBaseUrl()

addRouteMiddleware('form-handler', async () => {
if (import.meta.server) {
fago marked this conversation as resolved.
Show resolved Hide resolved
const event = useRequestEvent()
if (event && event.node.req.method === 'POST') {
const formData = await readFormData(event)

if (formData && formData.get('target_url')) {
const targetUrl = formData.get('target_url')
const response = await $fetch.raw(drupalBaseUrl + ceApiEndpoint + targetUrl, {
fago marked this conversation as resolved.
Show resolved Hide resolved
method: 'POST',
body: formData,
})

event.context.nitro.response = {
fago marked this conversation as resolved.
Show resolved Hide resolved
_data: response._data,
headers: Object.fromEntries(response.headers.entries()),
}
} else {
throw createError({
statusCode: 400,
statusMessage: 'Bad Request',
message: 'The request contains invalid form data or no form data at all.',
})
}
}
}
}, { global: true })
})