distributed-computing/tasks/voronkova-es/lab_3/worker-1/Program.cs
2023-12-18 23:14:17 +04:00

88 lines
2.2 KiB
C#

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<DrugstoreService>();
// Add Swagger services
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.MapGet("/", (DrugstoreService service) => service.GetAll());
app.MapGet("/drugstores/{id}", (DrugstoreService service, Guid id) =>
{
var drugstore = service.Get(id);
return drugstore is not null ? Results.Ok(drugstore) : Results.NotFound();
});
app.MapPost("/drugstores", (DrugstoreService service, Drugstore drugstore) =>
{
service.Create(drugstore);
return Results.Created($"/drugstores/{drugstore.Id}", drugstore);
});
app.MapPut("/drugstores/{id}", (DrugstoreService service, Drugstore updatedDrugstore, Guid id) =>
{
var drugstore = service.Get(id);
if (drugstore is null) return Results.NotFound();
service.Update(updatedDrugstore);
return Results.Ok(updatedDrugstore);
});
app.MapDelete("/drugstores/{id}", (DrugstoreService service, Guid id) =>
{
service.Delete(id);
return Results.Ok();
});
app.Run();
public record Drugstore(Guid Id, string Name, string Address);
public class DrugstoreService
{
private readonly List<Drugstore> _drugstores = new();
public List<Drugstore> GetAll() => _drugstores;
public Drugstore? Get(Guid id) => _drugstores.FirstOrDefault(d => d.Id == id);
public void Create(Drugstore newDrugstore) => _drugstores.Add(newDrugstore);
public void Update(Drugstore updatedDrugstore)
{
var index = _drugstores.FindIndex(d => d.Id == updatedDrugstore.Id);
if (index == -1) return;
_drugstores[index] = updatedDrugstore;
}
public void Delete(Guid id)
{
var drugstore = Get(id);
if (drugstore is null) return;
_drugstores.Remove(drugstore);
}
}