# Queries from any Effect (https://effetch-query.monarcode.dev/docs/queries/without-effetch)

Not every query is an Effetch endpoint. You might call your Effetch client
yourself, use Effect's own `HttpClient`, or read a database or local
storage. Any Effect can be a query: `Query.make` defines one query, and
`Query.family` one query per argument. This page shows both, and what you
write yourself that an endpoint would give you.

Two things stay the same as with endpoints. Name the services your
queries use in `Register`, as
[1. Describe your API](https://effetch-query.monarcode.dev/docs/getting-started#1-describe-your-api) does,
and give the client a layer that provides them. The
[Use Effect's HttpClient](https://effetch-query.monarcode.dev/docs/queries/without-effetch#use-effects-httpclient) sample shows both.

## Call your Effetch client yourself

`Query.make` takes a key and a `run` Effect. `Query.family` takes a key
and a `run` function of one argument, and returns a family: a function
that gives you the query for each argument. This file calls `ApiClient`
from [Getting started](https://effetch-query.monarcode.dev/docs/getting-started) directly:

```ts
import * as Schema from "effect/Schema";

import { Query } from "@monarcode/effetch-query";

import { ApiClient } from "./api.js";

const User = Schema.Struct({ id: Schema.Finite, name: Schema.String });

export const me = Query.make({
  key: ["users", "me"],
  run: ApiClient.use((client) => client.get("/users/me", { output: User })),
});
// me is the query keyed ["users", "me"]

export const user = Query.family({
  key: ["users", "detail"],
  run: (id: number) =>
    ApiClient.use((client) =>
      client.get("/users/:id", { params: { id }, output: User }),
    ),
  staleTime: "1 minute",
});
// user(1) is the query keyed ["users", "detail", 1]
```

These work the same as endpoint queries, with the same typed errors from
Effetch. Each takes the same options too, such as `staleTime`, which
[Query options](https://effetch-query.monarcode.dev/docs/queries/options) lists.

## Use Effect's HttpClient

Without Effetch, register Effect's `HttpClient` as your service, and call
it from `run`:

```ts
import * as Effect from "effect/Effect";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientResponse from "effect/http/HttpClientResponse";
import * as Schema from "effect/Schema";

import { Query, QueryClient } from "@monarcode/effetch-query";

const Todo = Schema.Struct({
  id: Schema.Finite,
  title: Schema.String,
  done: Schema.Boolean,
});

declare module "@monarcode/effetch-query" {
  interface Register {
    readonly services: HttpClient.HttpClient;
  }
}

export const todo = Query.family({
  key: ["todos", "detail"],
  run: (id: number) =>
    HttpClient.get(`https://api.example.com/todos/${id}`).pipe(
      Effect.flatMap(HttpClientResponse.filterStatusOk),
      Effect.flatMap(HttpClientResponse.schemaBodyJson(Todo)),
    ),
  schema: { success: Todo },
});
// todo(1): Query<Todo, HttpClientError | SchemaError>,
// keyed ["todos", "detail", 1]

// Sends requests with the browser's `fetch`.
export const queryClient = QueryClient.make({ layer: FetchHttpClient.layer });
```

The query's error is whatever its Effect fails with, here Effect's
`HttpClientError` and `SchemaError`, typed all the way to the component.

## Use a service of your own

A query can use any service you register, such as a store that wraps your
API. This file defines a list, a detail family, and a query that reads the
list:

```ts
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";

import { Query } from "@monarcode/effetch-query";

const Todo = Schema.Struct({
  id: Schema.Finite,
  title: Schema.String,
  done: Schema.Boolean,
});
type Todo = typeof Todo.Type;

class TodoNotFound extends Data.TaggedError("TodoNotFound")<{
  readonly id: number;
}> {}

// Any service: an HttpClient wrapper, a database, local storage…
class TodoStore extends Context.Service<
  TodoStore,
  {
    readonly list: Effect.Effect<ReadonlyArray<Todo>>;
    readonly get: (id: number) => Effect.Effect<Todo, TodoNotFound>;
  }
>()("TodoStore") {}

declare module "@monarcode/effetch-query" {
  interface Register {
    readonly services: TodoStore;
  }
}

export const todos = Query.make({
  key: ["todos", "list"],
  run: TodoStore.use((store) => store.list),
  // How the value crosses to the browser, and how entities find todos in it.
  schema: { success: Schema.Array(Todo) },
});

export const todo = Query.family({
  key: ["todos", "detail"],
  run: (id: number) => TodoStore.use((store) => store.get(id)),
  staleTime: "1 minute",
});
// todo(1): Query<Todo, TodoNotFound>, keyed ["todos", "detail", 1]

// Reads the list, and runs again when the list's value changes.
export const openCount = Query.make({
  key: ["todos", "open-count"],
  run: (ctx) =>
    Effect.map(
      ctx.result(todos),
      (list) => list.filter((item) => !item.done).length,
    ),
});
```

A mutation from your own Effect works the same way, with `Mutation.make`,
as [Define a mutation](https://effetch-query.monarcode.dev/docs/mutations) shows.

## What you write yourself

An endpoint gives a query its key and its schema. Without one, you write
them:

- **The key.** A family's key is its `key` followed by the argument:
  `todo(1)` is `["todos", "detail", 1]`. Arguments are compared by value,
  so `todo(1) === todo(1)`. [Query keys](https://effetch-query.monarcode.dev/docs/queries/keys) explains how
  keys match.
- **The schema.** Give a query a `schema` to render it on the server and
  to let [entities](https://effetch-query.monarcode.dev/docs/cache/entities) find records in it. An endpoint
  takes it from its `output`. In
  [Use a service of your own](https://effetch-query.monarcode.dev/docs/queries/without-effetch#use-a-service-of-your-own), `todos` has
  one and `todo` doesn't, so `todo` is fetched in the browser.
- **What it reads.** `run` can read other queries through `ctx.result`,
  as `openCount` does. See
  [Queries that read other queries](https://effetch-query.monarcode.dev/docs/queries/dependent).

Hooks, mutations, the cache and server rendering work the same as with
endpoints. The parts of these docs about `fromClient` don't apply: keys
from a route and `fromClient`'s options. A call you make with your Effetch
client still fails with the errors its `statusErrors` declare, as
[Errors by status](https://effetch-query.monarcode.dev/docs/queries/errors#errors-by-status) shows for
endpoints.

## What's next

- [Query keys](https://effetch-query.monarcode.dev/docs/queries/keys): how keys are built, and how a target
  matches them.
- [Infinite queries](https://effetch-query.monarcode.dev/docs/queries/infinite): page through a list with
  `InfiniteQuery.make` and `InfiniteQuery.family`.
- [Queries from a stream](https://effetch-query.monarcode.dev/docs/queries/streams): make a query from a
  `Stream` with `Query.stream` and `Query.streamFamily`.
- [Query options](https://effetch-query.monarcode.dev/docs/queries/options): every option `Query.make` and
  `Query.family` take.