# A CRUD resource

**Problem.** You need a `User` that is stored, created, read, updated, listed and deleted, without copying the field list five times.

**Pattern.** One stored _entity_ schema, several _projections_ of it, and one operation per role.

```ts
import {
  body,
  dryv,
  field,
  http,
  operation,
  path,
  projection,
  property,
  queryObject,
  respond,
  schema,
  storage,
} from "@dryvcode/author";

const core = dryv.group({ name: "core" });
const values = core.properties({
  UserId: property.string.uuid(),
  DisplayName: property.string(),
  Timestamp: property.string(),
  Count: property.number.integer({ range: { min: 0 } }),
  UserStatus: property.enum({ active: "active", suspended: "suspended" }),
});
const userManagement = core.feature("UserManagement");

// 1. The stored shape: the single source of truth for fields
const stored = userManagement.schemas({
  UserProfile: schema({
    id: field(values.UserId)
      .system()
      .query({ filter: ["equal"] }),
    displayName: field(values.DisplayName).query({ filter: ["equal"] }),
    status: field(values.UserStatus).optional(),
    createdAt: field(values.Timestamp)
      .system()
      .query({ filter: ["equal"] }),
  })
    .role("entity")
    .facets({ storage: storage("UserStore").primaryKey("id") }),
});

// 2. API shapes derived from it
const users = userManagement.schemas({
  UserRead: schema({}).projection(
    projection(stored.UserProfile)
      .read()
      .pick("id", "displayName", "status", "createdAt"),
  ),
  CreateUserRequest: schema({}).projection(
    projection(stored.UserProfile).create().pick("displayName", "status"),
  ),
  UpdateUserRequest: schema({}).projection(
    projection(stored.UserProfile).edit().pick("displayName", "status"),
  ),
  UserQuery: schema({}).projection(
    projection(stored.UserProfile)
      .query()
      .pick("id", "displayName", "createdAt")
      .rename({ id: "userId" })
      .usage({
        userId: { optional: true },
        displayName: { optional: true },
        createdAt: { optional: true },
      }),
  ),
  UserPage: schema({
    items: field(stored.UserProfile).array(),
    total: field(values.Count),
  }).role("response"),
});

// 3. One operation per role
const CreateUser = operation()
  .role("create")
  .input(users.CreateUserRequest)
  .output(users.UserRead);
const GetUser = operation()
  .role("detail")
  .input({ id: values.UserId })
  .output(users.UserRead);
const ListUsers = operation()
  .role("list")
  .input(users.UserQuery)
  .output(users.UserPage);
const UpdateUser = operation()
  .role("update")
  .input({ id: values.UserId, update: users.UpdateUserRequest })
  .output(users.UserRead);
const DeleteUser = operation().role("delete").input({ id: values.UserId });

// 4. Transport is a facet, not part of the operation's meaning
CreateUser.facets({
  http: http("POST", "/users")
    .input(CreateUser.in, body())
    .output(CreateUser.out, respond(201)),
});
GetUser.facets({
  http: http("GET", "/users/{id}")
    .input(GetUser.in.id, path("id"))
    .output(GetUser.out, respond(200)),
});
ListUsers.facets({
  http: http("GET", "/users")
    .input(ListUsers.in, queryObject())
    .output(ListUsers.out, respond(200)),
});
UpdateUser.facets({
  http: http("PATCH", "/users/{id}")
    .input(UpdateUser.in.id, path("id"))
    .input(UpdateUser.in.update, body())
    .output(UpdateUser.out, respond(200)),
});
DeleteUser.facets({
  http: http("DELETE", "/users/{id}").input(DeleteUser.in.id, path("id")),
});

userManagement.operations({
  CreateUser,
  GetUser,
  ListUsers,
  UpdateUser,
  DeleteUser,
});

export default dryv
  .app({ name: "coreJourney" })
  .groups(core)
  .facets({ http: { root: "/api" } });
```

## Why it is shaped this way

| Choice                                                         | Reason                                                                                        |
| -------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `.system()` on `id` and `createdAt`                            | Clients must not send them; the `create` and `edit` projections leave them out automatically  |
| `projection(...).read() / .create() / .edit() / .query()`      | The purpose tells packs what the shape is for (a response, a request body, a patch, a filter) |
| `.rename({ id: "userId" })`                                    | The query shape can use friendlier names without forking the entity                           |
| `.usage({ ... optional })`                                     | Query parameters are optional even when the stored field is required                          |
| `role("create" \| "detail" \| "list" \| "update" \| "delete")` | Packs choose HTTP verbs, status codes and handler shapes from roles                           |
| HTTP as a `facet`                                              | The same operation can later gain a queue or CLI facet without changing meaning               |

## Try it

Copy the file into `dryv/contracts/index.ts`, then:

```bash
dryv build && dryv validate && dryv plan
```

The maintained, tested version of this example lives in `sdk/_examples/projects/core-journey` in the repository.
