Skip to content

Latest commit

 

History

History
194 lines (150 loc) · 7.5 KB

actions.md

File metadata and controls

194 lines (150 loc) · 7.5 KB

Actions

Astro docs: Actions

An action is a class implementing IAstroAction<TInput, TOutput>. The interface is what makes it one — nothing is declared, and no attribute is required.

In TypeScript

// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro:schema';

export const server = {
  createComment: defineAction({
    input: z.object({ postId: z.string(), text: z.string() }),
    handler: async ({ postId, text }) => {
      if (!text.trim()) throw new ActionError({ code: 'BAD_REQUEST', message: 'Comment text is required.' });
      return { id: crypto.randomUUID(), status: 'created' };
    },
  }),
};

In C#

public sealed record CreateCommentInput(string PostId, string Text);
public sealed record CreateCommentOutput(string Id, string Status);

public sealed class CreateComment : IAstroAction<CreateCommentInput, CreateCommentOutput>
{
    public Task<CreateCommentOutput> HandleAsync(CreateCommentInput input, ActionContext context)
    {
        if (string.IsNullOrWhiteSpace(input.Text))
            throw ActionException.BadRequest("Comment text is required.");

        return Task.FromResult(new CreateCommentOutput(Guid.NewGuid().ToString("n")[..8], "created"));
    }
}

Re-export them once, and they are ordinary Astro actions from then on — the /_actions endpoint, actions.x() calls, Astro.getActionResult(), form handling and ActionError mapping all come from Astro:

// src/actions/index.ts
export { server } from 'astrosharp:actions';

Input validation

Derived from TInput. AstroSharp reflects the C# type into the Zod validator Astro wants, so isInputError() is true for a bad payload and a form gets per-field messages, without writing the shape twice.

int becomes a whole number, DateTime a coerced date, string? and int? optional-and-nullable, arrays and nested records their own shapes. Opt out with [AstroAction(ValidateInput = false)], in which case the payload reaches the handler unvalidated and the handler owns the checking.

Constraints, from DataAnnotations

A type says what shape a value has; it cannot say that a string is an email address or that a number is between 1 and 5. Zod says both, and the C# spelling of the second half is System.ComponentModel.DataAnnotations:

input: z.object({
  email: z.string().email(),
  username: z.string().min(3).max(12),
  rating: z.number().int().min(1).max(5),
}),
public sealed record SignupInput(
    [EmailAddress] string Email,
    [StringLength(12, MinimumLength = 3)] string Username,
    [Range(1, 5)] int Rating);
Attribute Becomes
[EmailAddress], [Url] the matching Zod string format
[StringLength(max, MinimumLength = min)] .min() and .max() on a string
[MinLength], [MaxLength] length on a string, element count on an array
[Range(min, max)] .min() / .max() on a number
[RegularExpression] .regex(), anchored — DataAnnotations matches the whole value
[Required] overrules the type's own nullability, and rejects "" unless AllowEmptyStrings

They work on a positional record's parameters as well as on properties, so the shape most inputs are written in needs no [property: ]. They reach content collection schemas the same way — see Content collections.

This is what makes the per-field messages above worth having: without it a derived validator can report that a field is not a string, and never that it is not an email address, so a form's error messages had to come from the handler throwing — which is one message for the whole submission rather than one against the input the visitor got wrong.

Form actions

public sealed record ImportInput(FormFile Csv, string[] Labels);

[AstroAction(Accept = "form")]
public sealed class ImportCsv : IAstroAction<ImportInput, ImportOutput>
{
    public Task<ImportOutput> HandleAsync(ImportInput input, ActionContext context)
    {
        var text = input.Csv.Text();          // also: .Bytes(), .Name, .ContentType, .Size
        return Task.FromResult(new ImportOutput(input.Labels.Length, text.Length));
    }
}

Because the validator describes the shape, Astro reads a repeated field with getAll rather than keeping only its last value, and a file field stays a file.

Reading the result

---
// .astro
const result = Astro.getActionResult(actions.subscribe);
---
@code {
    private ActionResult? _result;

    protected override void OnInitialized() => _result = Astro.GetActionResult("subscribe");

    private string? EmailError =>
        _result?.Error is { } e && e.Fields.TryGetValue("email", out var m) && m.Count > 0 ? m[0] : null;
}

<form method="POST" action="/_actions/subscribe">
  <input type="email" name="email" aria-invalid="@(EmailError is not null ? "true" : "false")" />
  @if (EmailError is not null) { <p class="error">@EmailError</p> }
  <button type="submit">Subscribe</button>
</form>

@if (_result is { Ok: true }) { <p>@(_result.GetData<SubscribeOutput>()?.Message)</p> }

By name, since C# has no reference to the action function. The name is checked, so a page asking for one action does not see another's result.

GetData<T>() deserializes the returned value; Error carries the code, the message, and Fields — the per-field messages a failed validator produced. Error.IsInputError is true exactly when there are field messages, which is what isInputError() means in JavaScript.

Errors

ActionException maps onto Astro's error codes:

throw ActionException.BadRequest("...");
throw ActionException.Unauthorized("...");
throw ActionException.NotFound("...");
throw new ActionException("CONFLICT", "...");     // any code

Limitations

Uploads are held in memory across the process boundary, which suits avatars and CSV imports. Post large files to an endpoint instead.

Astro.callAction() has no C# equivalent, and does not need one: a C# page can call its action class directly. Doing so skips the generated validator, so the page owns its own checking.

Actions run per request, so in production they need experimental.serverRendering — even on an otherwise static site.

The rest of astro:actions stays on the JavaScript side, where it already works against C# actions because they are ordinary Astro actions once re-exported: actions.x.orThrow(), actions.x.queryString for a form's action attribute, isInputError() / isActionError(), and getActionContext() for middleware that intercepts a submission. Only getActionResult has a C# mirror, because only that one is read during a render.

References are not allowed in an action input. [References] is a content-collection feature and fails the build here — there is no store behind an action to resolve against.

A constraint with no DataAnnotations spelling cannot be expressed, and unlike a content collection there is nowhere to fall back to: a collection composes with a schema: written in content.config.ts, while an action is re-exported whole and has no seam for a hand-written Zod schema. So .refine(), .transform(), .default(), discriminated unions and cross-field rules ("confirm matches password") belong in the handler, which throws ActionException.BadRequest — one message for the submission rather than one per field. The table above is the whole of what reaches the validator.