Skip to content

Instantly share code, notes, and snippets.

@IEvangelist
Last active December 2, 2021 06:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IEvangelist/0ca45c135d956f207384e0c0075fbb6d to your computer and use it in GitHub Desktop.
Save IEvangelist/0ca45c135d956f207384e0c0075fbb6d to your computer and use it in GitHub Desktop.
Minimal API — Azure Cosmos DB repository-pattern .NET SDK
// GitHub: 👨🏽‍💻 https://github.com/ievangelist
// Twitter: 🤓 https://twitter.com/davidpine7
// SDK: 🛠️ https://github.com/IEvangelist/azure-cosmos-dotnet-repository
using System.ComponentModel.DataAnnotations;
using Microsoft.Azure.CosmosRepository;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCosmosRepository();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.MapGet("/", () => "Hello World!");
app.MapGet("/hello", () => new { Hello = "World" });
app.MapGet("/todos", (IRepository<Todo> repo) => repo.GetByQueryAsync("SELECT * FROM Todos"));
app.MapGet("/todos/complete", (IRepository<Todo> repo) => repo.GetAsync(todo => todo.IsComplete));
app.MapGet("/todos/incomplete", (IRepository<Todo> repo) => repo.GetAsync(todo => !todo.IsComplete));
app.MapGet("/todos/{id}", async (string id, IRepository<Todo> repo) =>
{
var todo = await repo.GetAsync(id);
return todo is not null ? Results.Ok(todo) : Results.NotFound();
});
app.MapPost("/todos", async (Todo todo, IRepository<Todo> repo) =>
{
if (!MinimalValidation.TryValidate(todo, out var errors))
return Results.ValidationProblem(errors);
var newTodo = await repo.CreateAsync(todo);
return Results.Created($"/todos/{newTodo.Id}", newTodo);
});
app.MapPut("/todos/{id}", async (string id, Todo todo, IRepository<Todo> repo) =>
{
todo.Id = id;
if (!MinimalValidation.TryValidate(todo, out var errors))
return Results.ValidationProblem(errors);
todo = await repo.UpdateAsync(todo);
return Results.NoContent();
});
app.MapPut("/todos/{id}/mark-complete", async (string id, IRepository<Todo> repo) =>
{
var todo = await repo.GetAsync(id);
if (todo is null) return Results.NotFound();
todo.IsComplete = true;
_ = await repo.UpdateAsync(todo);
return Results.NoContent();
});
app.MapPut("/todos/{id}/mark-incomplete", async (string id, IRepository<Todo> repo) =>
{
var todo = await repo.GetAsync(id);
if (todo is null) return Results.NotFound();
todo.IsComplete = false;
_ = await repo.UpdateAsync(todo);
return Results.NoContent();
});
app.MapDelete("/todos/{id}", (string id, IRepository<Todo> repo) => repo.DeleteAsync(id));
await app.RunAsync();
class Todo : Item
{
[Required]
public string? Title { get; set; }
public bool IsComplete { get; set; }
}
@IEvangelist
Copy link
Author

@davidfowl
Copy link

Make this a repository plz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment