Skip to content

$api

import { $api } from "dreamkit";

You will be able to define a parameter schema to validate your input data and consume objects registered by services and middlewares.


Definition

const $api: {
title(value: string): typeof $api;
params(value: object): typeof $api;
self(value: object): typeof $api;
cache(key?: string): typeof $api;
create(cb: (this: object, params: object) => any): {
title: string;
params: object;
(this: object, params: object): any;
};
};

title

Stores the API title.

This value can be reused by others.

const login = $api.title("Login").create(() => {});
console.log(login.title); // "Login"

params

Defines the input parameter scheme of the API.

Parameters are validated on the client and on the server, and the schema can be reused after the function is created.

If the parameters are not valid, the remote request will not be made and an error will be thrown.

const login = $api
.params({ username: s.string(), password: s.string() })
.create(() => {});
login.params; // { username: s.string(), password: s.string() }

self

Consumes dependencies registered in the IoC context so that they can be used internally by the function.

By default there are a number of registered objects available:

const fetchContentType = $api.self({ Headers }).create(function () {
return this.headers.get("Content-Type");
});

cache

Temporarily saves the request and response to avoid unnecessary multiple calls.

Internally calls the query function from @solidjs/router.

create

Create the API function with the configured parameters and instance.


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={send.title} />
{send.error && <p>Error: {send.error.message}</p>}
{send.state === "success" && <p>Success</p>}
</>
);
});