ajout projet api

master
enjolys 3 years ago
parent bc3680793d
commit f157bdead5

@ -0,0 +1,213 @@
namespace Minecraft.Crafting.Api.Controllers
{
using Microsoft.AspNetCore.Mvc;
using Minecraft.Crafting.Api.Models;
using System.Text.Json;
using System.Text.Json.Serialization;
[ApiController]
[Route("api/[controller]")]
public class CraftingController : ControllerBase
{
private readonly JsonSerializerOptions _jsonSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
};
[HttpPost]
[Route("")]
public Task Add(Item item)
{
var data = JsonSerializer.Deserialize<List<Item>>(System.IO.File.ReadAllText("Data/items.json"), _jsonSerializerOptions);
data.Add(item);
System.IO.File.WriteAllText("Data/items.json", JsonSerializer.Serialize(data, _jsonSerializerOptions));
return Task.CompletedTask;
}
[HttpGet]
[Route("count")]
public Task<int> Count()
{
var data = JsonSerializer.Deserialize<List<Item>>(System.IO.File.ReadAllText("Data/items.json"), _jsonSerializerOptions);
return Task.FromResult(data.Count());
}
[HttpDelete]
[Route("{id}")]
public Task Delete(int id)
{
var data = JsonSerializer.Deserialize<List<Item>>(System.IO.File.ReadAllText("Data/items.json"), _jsonSerializerOptions);
var item = data?.FirstOrDefault(w => w.Id == id);
if (item == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
data.Remove(item);
System.IO.File.WriteAllText("Data/items.json", JsonSerializer.Serialize(data, _jsonSerializerOptions));
return Task.CompletedTask;
}
[HttpGet]
[Route("{id}")]
public Task<Item> GetById(int id)
{
var data = JsonSerializer.Deserialize<List<Item>>(System.IO.File.ReadAllText("Data/items.json"), _jsonSerializerOptions);
var item = data?.FirstOrDefault(w => w.Id == id);
if (item == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
return Task.FromResult(item);
}
[HttpGet]
[Route("recipe")]
public Task<List<Recipe>> GetRecipe()
{
if (!System.IO.File.Exists("Data/convert-recipes.json"))
{
ConvertRecipes();
}
var data = JsonSerializer.Deserialize<List<Recipe>>(System.IO.File.ReadAllText("Data/convert-recipes.json"), _jsonSerializerOptions);
return Task.FromResult(data);
}
private void ConvertRecipes()
{
var data = JsonSerializer.Deserialize<List<Item>>(System.IO.File.ReadAllText("Data/items.json"), _jsonSerializerOptions);
if (data == null)
{
return;
}
var recipes = Recipes.FromJson(System.IO.File.ReadAllText("Data/recipes.json"));
var items = new List<Recipe>();
foreach (var recipe in recipes.SelectMany(s => s.Value))
{
if (recipe.InShape == null)
{
continue;
}
var giveItem = data.FirstOrDefault(w => w.Id == recipe.Result.Id);
if (giveItem == null)
{
continue;
}
items.Add(new Recipe
{
Give = new Item { DisplayName = giveItem.DisplayName, Name = giveItem.Name },
Have = new List<List<string>>
{
new()
{
GetItemName(data, recipe.InShape, 0, 0),
GetItemName(data, recipe.InShape, 0, 1),
GetItemName(data, recipe.InShape, 0, 2)
},
new()
{
GetItemName(data, recipe.InShape, 1, 0),
GetItemName(data, recipe.InShape, 1, 1),
GetItemName(data, recipe.InShape, 1, 2)
},
new()
{
GetItemName(data, recipe.InShape, 2, 0),
GetItemName(data, recipe.InShape, 2, 1),
GetItemName(data, recipe.InShape, 2, 2)
}
}
});
}
System.IO.File.WriteAllText("Data/convert-recipes.json", JsonSerializer.Serialize(items, _jsonSerializerOptions));
}
[HttpGet]
[Route("")]
public Task<List<Item>> List(int currentPage, int pageSize)
{
var data = JsonSerializer.Deserialize<List<Item>>(System.IO.File.ReadAllText("Data/items.json"), _jsonSerializerOptions);
return Task.FromResult(data.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList());
}
[HttpPut]
[Route("{id}")]
public Task Update(int id, Item item)
{
var data = JsonSerializer.Deserialize<List<Item>>(System.IO.File.ReadAllText("Data/items.json"), _jsonSerializerOptions);
var itemOriginal = data?.FirstOrDefault(w => w.Id == id);
if (itemOriginal == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
itemOriginal.Id = item.Id;
itemOriginal.Name = item.Name;
itemOriginal.CreatedDate = item.CreatedDate;
itemOriginal.DisplayName = item.DisplayName;
itemOriginal.EnchantCategories = item.EnchantCategories;
itemOriginal.MaxDurability = item.MaxDurability;
itemOriginal.RepairWith = item.RepairWith;
itemOriginal.StackSize = item.StackSize;
itemOriginal.UpdatedDate = item.UpdatedDate;
System.IO.File.WriteAllText("Data/items.json", JsonSerializer.Serialize(data, _jsonSerializerOptions));
return Task.CompletedTask;
}
private static string GetItemName(List<Item> items, InShape[][] inShape, int line, int row)
{
if (inShape.Length < line + 1)
{
return null;
}
if (inShape[line].Length < row + 1)
{
return null;
}
var id = inShape[line][row].Integer ?? inShape[line][row].IngredientClass?.Id;
if (id == null)
{
return null;
}
return GetItemName(items, id.Value);
}
private static string GetItemName(List<Item> items, long id)
{
var item = items.FirstOrDefault(w => w.Id == id);
return item?.Name;
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,19 @@
namespace Minecraft.Crafting.Api.Definitions
{
using System.Text.Json.Serialization;
public class RecipeDefinition
{
//[JsonPropertyName("ingredients")]
//public IngredientElement[] Ingredients { get; set; }
[JsonPropertyName("result")]
public RecipeResultDefinition Result { get; set; }
[JsonPropertyName("inShape")]
public RecipeInShapeDefinition[][] InShape { get; set; }
//[JsonPropertyName("outShape")]
//public long?[][] OutShape { get; set; }
}
}

@ -0,0 +1,13 @@
namespace Minecraft.Crafting.Api.Definitions
{
using System.Text.Json.Serialization;
public class RecipeInShapeDefinition
{
[JsonPropertyName("id")]
public long Id { get; set; }
[JsonPropertyName("metadata")]
public long Metadata { get; set; }
}
}

@ -0,0 +1,16 @@
namespace Minecraft.Crafting.Api.Definitions
{
using System.Text.Json.Serialization;
public class RecipeResultDefinition
{
[JsonPropertyName("count")]
public long Count { get; set; }
[JsonPropertyName("id")]
public long Id { get; set; }
[JsonPropertyName("metadata")]
public long Metadata { get; set; }
}
}

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
<ItemGroup>
<Content Update="Data\items.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

@ -0,0 +1,21 @@
namespace Minecraft.Crafting.Api.Models
{
public class Item
{
public Item()
{
EnchantCategories = new List<string>();
RepairWith = new List<string>();
}
public DateTime CreatedDate { get; set; }
public string DisplayName { get; set; }
public List<string> EnchantCategories { get; set; }
public int Id { get; set; }
public int MaxDurability { get; set; }
public string Name { get; set; }
public List<string> RepairWith { get; set; }
public int StackSize { get; set; }
public DateTime? UpdatedDate { get; set; }
}
}

@ -0,0 +1,10 @@
namespace Minecraft.Crafting.Api
{
using Minecraft.Crafting.Api.Models;
public class Recipe
{
public Item Give { get; set; }
public List<List<string>> Have { get; set; }
}
}

@ -0,0 +1,25 @@
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:51530",
"sslPort": 44598
}
},
"profiles": {
"Minecraft.Crafting.Api": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7234;http://localhost:5234",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

@ -0,0 +1,177 @@
namespace Minecraft.Crafting.Api
{
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Globalization;
using JsonConverter = Newtonsoft.Json.JsonConverter;
using JsonSerializer = Newtonsoft.Json.JsonSerializer;
public struct IngredientElement
{
public IngredientClass IngredientClass;
public long? Integer;
public static implicit operator IngredientElement(IngredientClass IngredientClass) => new IngredientElement { IngredientClass = IngredientClass };
public static implicit operator IngredientElement(long Integer) => new IngredientElement { Integer = Integer };
}
public struct InShape
{
public IngredientClass IngredientClass;
public long? Integer;
public bool IsNull => IngredientClass == null && Integer == null;
public static implicit operator InShape(IngredientClass IngredientClass) => new InShape { IngredientClass = IngredientClass };
public static implicit operator InShape(long Integer) => new InShape { Integer = Integer };
}
public static class Serialize
{
public static string ToJson(this Dictionary<string, Recipes[]> self) => JsonConvert.SerializeObject(self, Converter.Settings);
}
public class IngredientClass
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("metadata")]
public long Metadata { get; set; }
}
public partial class Recipes
{
[JsonProperty("ingredients", NullValueHandling = NullValueHandling.Ignore)]
public IngredientElement[] Ingredients { get; set; }
[JsonProperty("inShape", NullValueHandling = NullValueHandling.Ignore)]
public InShape[][] InShape { get; set; }
[JsonProperty("outShape", NullValueHandling = NullValueHandling.Ignore)]
public long?[][] OutShape { get; set; }
[JsonProperty("result")]
public Result Result { get; set; }
}
public partial class Recipes
{
public static Dictionary<string, Recipes[]> FromJson(string json) => JsonConvert.DeserializeObject<Dictionary<string, Recipes[]>>(json, Converter.Settings);
}
public class Result
{
[JsonProperty("count")]
public long Count { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("metadata")]
public long Metadata { get; set; }
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
InShapeConverter.Singleton,
IngredientElementConverter.Singleton,
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
internal class IngredientElementConverter : JsonConverter
{
public static readonly IngredientElementConverter Singleton = new IngredientElementConverter();
public override bool CanConvert(Type t) => t == typeof(IngredientElement) || t == typeof(IngredientElement?);
public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.Integer:
var integerValue = serializer.Deserialize<long>(reader);
return new IngredientElement { Integer = integerValue };
case JsonToken.StartObject:
var objectValue = serializer.Deserialize<IngredientClass>(reader);
return new IngredientElement { IngredientClass = objectValue };
}
throw new Exception("Cannot unmarshal type IngredientElement");
}
public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
{
var value = (IngredientElement)untypedValue;
if (value.Integer != null)
{
serializer.Serialize(writer, value.Integer.Value);
return;
}
if (value.IngredientClass != null)
{
serializer.Serialize(writer, value.IngredientClass);
return;
}
throw new Exception("Cannot marshal type IngredientElement");
}
}
internal class InShapeConverter : JsonConverter
{
public static readonly InShapeConverter Singleton = new InShapeConverter();
public override bool CanConvert(Type t) => t == typeof(InShape) || t == typeof(InShape?);
public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.Null:
return new InShape { };
case JsonToken.Integer:
var integerValue = serializer.Deserialize<long>(reader);
return new InShape { Integer = integerValue };
case JsonToken.StartObject:
var objectValue = serializer.Deserialize<IngredientClass>(reader);
return new InShape { IngredientClass = objectValue };
}
throw new Exception("Cannot unmarshal type InShape");
}
public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
{
var value = (InShape)untypedValue;
if (value.IsNull)
{
serializer.Serialize(writer, null);
return;
}
if (value.Integer != null)
{
serializer.Serialize(writer, value.Integer.Value);
return;
}
if (value.IngredientClass != null)
{
serializer.Serialize(writer, value.IngredientClass);
return;
}
throw new Exception("Cannot marshal type InShape");
}
}
}

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

@ -0,0 +1,23 @@
using ProjetBlazor.Modeles;
namespace ProjetBlazor.Services
{
public class DataApiService : IDataService
{
private readonly HttpClient _http;
public DataApiService(HttpClient http)
{
_http = http;
}
public async Task AddInPlaylist(Musique musique)
{
// Get the item
//var item = ItemFactory.Create(model);
// Save the data
await _http.PostAsJsonAsync("https://localhost:7234/api/", musique);
}
}
}

@ -0,0 +1,9 @@
using ProjetBlazor.Modeles;
namespace ProjetBlazor.Services
{
public interface IDataService
{
Task AddInPlaylist(Musique musique);
}
}
Loading…
Cancel
Save