Skip to content

$api

Description

API builder.

Import

import { $api } from "dreamkit";

Definition

declare const $api: {
params: (value: object) => typeof $api;
self: (value: object) => typeof $api;
create: (this: object, params: object) => any;
};

Examples

Simple server execution

import { $api, $route } from "dreamkit";
import { createResource } from "solid-js";
export const pid = $api.create(() => process.pid);
export default $route
.api({ pid })
.path("/")
.create(({ api }) => {
const [pid] = createResource(api.pid);
return <p>Process ID: {pid()}</p>;
});

Params validation

import { $api, $route, createAction, Input, s } from "dreamkit";
import { createSignal } from "solid-js";
export const send = $api
.title("Send")
.params({
name: s.string().min(1),
})
.create(function ({ name }) {
console.log("Received", { name });
});
export default $route
.api({ send })
.path("/")
.create(({ api }) => {
const [name, setName] = createSignal("");
const send = createAction(api.send).with({
get name() {
return name();
},
});
return (
<>
<Input value={name} onChange={setName} />
<button
onClick={send}
disabled={send.running}
children={api.send.title}
/>
{send.error && <p>Error: {JSON.stringify(send.error.cause)}</p>}
{send.state === "success" && <p>Success</p>}
</>
);
});