-
-
Notifications
You must be signed in to change notification settings - Fork 243
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(router): introduce server support for form actions #1346
Merged
Merged
Changes from 8 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
bbd35a6
feat(router): introduce support for form actions
brandonroberts f06f6fe
chore: define server actions, add post and get examples
brandonroberts 70a5514
fix: stringify url on redirect
brandonroberts dac4f86
fix: use Location header for redirects
brandonroberts 762ba6e
chore: remove response types
brandonroberts f5940fc
feat: re-run guards/resolvers on same url by default
brandonroberts f95b31f
chore: update search example
brandonroberts 8ecf449
chore: remove copy-pasta
brandonroberts 4aa1494
refactor: separate handling of methods in form action directive
brandonroberts 5b4ee8d
fix: update success emit for state
brandonroberts 9eaafad
Merge branch 'beta' into feat-form-actions-server
brandonroberts File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
import { Directive, inject, input, output } from '@angular/core'; | ||
import { Params, Router } from '@angular/router'; | ||
|
||
export type ActionResult = { | ||
type: string; | ||
}; | ||
|
||
@Directive({ | ||
selector: 'form[action],form[method]', | ||
host: { | ||
'(submit)': `submitted($event)`, | ||
}, | ||
standalone: true, | ||
}) | ||
export class FormAction { | ||
action = input<string>(''); | ||
onSuccess = output<unknown>(); | ||
onError = output<unknown>(); | ||
state = output< | ||
'submitting' | 'error' | 'redirect' | 'success' | 'navigate' | ||
>(); | ||
router = inject(Router); | ||
|
||
submitted($event: { target: HTMLFormElement } & Event) { | ||
this.state.emit('submitting'); | ||
$event.preventDefault(); | ||
const body = new FormData($event.target); | ||
const path = window.location.pathname; | ||
|
||
if ($event.target.method.toUpperCase() === 'GET') { | ||
const params: Params = {}; | ||
body.forEach((formVal, formKey) => { | ||
params[formKey] = formVal; | ||
}); | ||
this.state.emit('navigate'); | ||
this.router.navigate([path], { | ||
queryParams: params, | ||
onSameUrlNavigation: 'reload', | ||
}); | ||
} else { | ||
fetch(this.action() || `/api/_analog/pages${path}`, { | ||
method: $event.target.method, | ||
body, | ||
}) | ||
.then((res) => { | ||
if (res.ok) { | ||
if (res.redirected) { | ||
const redirectUrl = new URL(res.url).pathname; | ||
this.state.emit('redirect'); | ||
this.router.navigate([redirectUrl]); | ||
} else if (res.headers.get('Content-type') === 'application/json') { | ||
res.json().then((result) => { | ||
this.onSuccess.emit(result); | ||
this.state.emit('success'); | ||
}); | ||
} else { | ||
res.text().then((result) => { | ||
this.onSuccess.emit(result); | ||
this.onSuccess.emit('success'); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. shouldn't it be There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yep |
||
}); | ||
} | ||
} else { | ||
if (res.headers.get('X-Analog-Errors')) { | ||
res.json().then((errors: unknown) => { | ||
this.onError.emit(errors); | ||
this.state.emit('error'); | ||
}); | ||
} else { | ||
this.state.emit('error'); | ||
} | ||
} | ||
}) | ||
.catch((_) => { | ||
this.state.emit('error'); | ||
}); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import { Component, signal } from '@angular/core'; | ||
|
||
import { FormAction } from './form-action.directive'; | ||
|
||
type FormErrors = | ||
| { | ||
email?: string; | ||
} | ||
| undefined; | ||
|
||
@Component({ | ||
selector: 'app-newsletter-page', | ||
standalone: true, | ||
imports: [FormAction], | ||
template: ` | ||
<h3>Newsletter Signup</h3> | ||
|
||
@if (!signedUp()) { | ||
<form | ||
method="post" | ||
(onSuccess)="onSuccess()" | ||
(onError)="onError($any($event))" | ||
(onStateChange)="errors.set(undefined)" | ||
> | ||
<div> | ||
<label for="email"> Email </label> | ||
<input type="email" name="email" /> | ||
</div> | ||
|
||
<button class="button" type="submit">Submit</button> | ||
</form> | ||
|
||
@if( errors()?.email ) { | ||
<p>{{ errors()?.email }}</p> | ||
} } @else { | ||
<div>Thanks for signing up!</div> | ||
} | ||
`, | ||
}) | ||
export default class NewsletterComponent { | ||
signedUp = signal(false); | ||
errors = signal<FormErrors>(undefined); | ||
|
||
onSuccess() { | ||
this.signedUp.set(true); | ||
} | ||
|
||
onError(result?: FormErrors) { | ||
this.errors.set(result); | ||
console.log({ result }); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import { | ||
type PageServerAction, | ||
redirect, | ||
json, | ||
fail, | ||
} from '@analogjs/router/server/actions'; | ||
import { readFormData } from 'h3'; | ||
|
||
export function load() { | ||
return { | ||
loaded: true, | ||
}; | ||
} | ||
|
||
export async function action({ event }: PageServerAction) { | ||
const body = await readFormData(event); | ||
const email = body.get('email') as string; | ||
|
||
if (!email) { | ||
return fail(422, { email: 'Email is required' }); | ||
} | ||
|
||
if (email.length < 10) { | ||
return redirect('/'); | ||
} | ||
|
||
console.log({ email: body.get('email') }); | ||
|
||
return json({ type: 'success' }); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import { Component, computed } from '@angular/core'; | ||
import { toSignal } from '@angular/core/rxjs-interop'; | ||
import { injectLoad } from '@analogjs/router'; | ||
|
||
import { FormAction } from './form-action.directive'; | ||
import type { load } from './search.server'; | ||
|
||
@Component({ | ||
selector: 'app-search-page', | ||
standalone: true, | ||
imports: [FormAction], | ||
template: ` | ||
<h3>Search</h3> | ||
|
||
<form method="get"> | ||
<div> | ||
<label for="search"> Search </label> | ||
<input type="text" name="search" [value]="searchTerm()" /> | ||
</div> | ||
|
||
<button class="button" type="submit">Submit</button> | ||
</form> | ||
|
||
@if(searchTerm()) { | ||
<p>Search Term: {{ searchTerm() }}</p> | ||
} | ||
`, | ||
}) | ||
export default class NewsletterComponent { | ||
loader = toSignal(injectLoad<typeof load>(), { requireSync: true }); | ||
searchTerm = computed(() => this.loader().searchTerm); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import type { PageServerLoad } from '@analogjs/router'; | ||
import { getQuery } from 'h3'; | ||
|
||
export async function load({ event }: PageServerLoad) { | ||
const query = getQuery(event); | ||
console.log('loaded search', query['search']); | ||
|
||
return { | ||
loaded: true, | ||
searchTerm: `${query['search']}`, | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"lib": { | ||
"entryFile": "src/index.ts" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import type { H3Event, H3EventContext } from 'h3'; | ||
import type { $Fetch } from 'nitropack'; | ||
|
||
export type PageServerAction = { | ||
params: H3EventContext['params']; | ||
req: H3Event['node']['req']; | ||
res: H3Event['node']['res']; | ||
fetch: $Fetch; | ||
event: H3Event; | ||
}; | ||
|
||
export function fail<T = object>(status: number, errors: T) { | ||
return new Response(JSON.stringify(errors), { | ||
status, | ||
headers: { | ||
'X-Analog-Errors': 'true', | ||
}, | ||
}); | ||
} | ||
|
||
export function json<T = object>(data: T, config?: ResponseInit) { | ||
return new Response(JSON.stringify(data), { | ||
headers: { | ||
'Content-Type': 'application/json; charset=utf-8', | ||
}, | ||
...config, | ||
}); | ||
} | ||
|
||
export function redirect(url: string, config: number | ResponseInit = 302) { | ||
if (typeof config === 'number') { | ||
return new Response(null, { | ||
status: config, | ||
headers: { | ||
Location: `${url}`, | ||
}, | ||
}); | ||
} | ||
|
||
return new Response(null, { | ||
headers: { | ||
Location: `${url}`, | ||
}, | ||
...config, | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export { PageServerAction, json, redirect, fail } from './actions'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This comment was marked as resolved.
Sorry, something went wrong.