Skip to content
This repository was archived by the owner on Feb 16, 2023. It is now read-only.

CRUD Example

Fernando Escolar edited this page May 6, 2021 · 1 revision

We are going to define a full CRUD example using RoutingRecords to show how it feels:

Create

using RoutingRecords;
using static Microsoft.AspNetCore.Http.StatusCodes;

namespace SampleApp.Api.Todos
{
  public record CreateTodo(ITodoStore store)
    : Post("todos", async (req, res) =>
    {
      var todo = await req.FromJsonAsync<Todo>();
      if (todo == null)
      {
          res.Status(Status400BadRequest);
          return;
      }

      await store.InsertAsync(todo);
      await res
              .Status(Status201Created)
              .JsonAsync(new
              {
                  Ref = $"todos/{store.Counter}"
              });
    });
}

Read All

using System.Linq;
using RoutingRecords;
using static Microsoft.AspNetCore.Http.StatusCodes;

namespace SampleApp.Api.Todos
{
  public record ReadTodos(ITodoStore store)
    : Get("todos", async (req, res) =>
    {
      var todos = await store.GetAllAsync();
      if (!todos.Any())
      {
        res.Status(Status204NoContent);
        return;
      }

      await res.JsonAsync(todos);
    });
}

Read One

using RoutingRecords;
using static Microsoft.AspNetCore.Http.StatusCodes;

namespace SampleApp.Api.Todos
{
  public record ReadTodo(ITodoStore store)
    : Get("todos/{id:int}", async (req, res) =>
    {
      var id = int.Parse((string)req.RouteValues["id"]);
      var todo = await store.GetOneAsync(id);
      if (todo == null)
      {
        res.Status(Status404NotFound);
        return;
      }

      await res.JsonAsync(todo);
    });
}

Update

using RoutingRecords;
using static Microsoft.AspNetCore.Http.StatusCodes;

namespace SampleApp.Api.Todos
{
  public record UpdateTodo(ITodoStore store)
    : Put("todos/{id:int}", async (req, res) =>
    {
      var id = req.FromRoute<int>("id");
      var todo = await req.FromJsonAsync<Todo>();
      if (todo == null)
      {
        res.Status(Status400BadRequest);
        return;
      }

      await store.UpsertAsync(id, todo);
      await res.JsonAsync(todo);
    });
}

Delete

using System.Threading.Tasks;
using RoutingRecords;

namespace SampleApp.Api.Todos
{
  public record DeleteTodo(ITodoStore store)
    : Delete("todos/{id:int}", (req, res) =>
    {
      var id = req.FromRoute<int>("id");
      return store.DeleteAsync(id);
    });
}

Clone this wiki locally