refactor helpers usage into extensions usage

This commit is contained in:
nugroho 2025-05-17 03:54:57 +07:00
parent 23d5391090
commit c84da9336a

View File

@ -11,21 +11,22 @@ public static partial class APIHandler
//============MISC================= //============MISC=================
.Map("/updatecache",cache=>{ .Map("/updatecache",cache=>{
cache.Run(async runner=>{ cache.Run(async runner=>{
_ = await UpdateCache(); await UpdateCache();
await WriteJsonResponse(runner,StatusCodes.Status200OK,"Cache Updated."); await runner.WriteJsonResponse(StatusCodes.Status200OK,"Cache Updated.");
}); });
}) })
//===========UNITS================= //===========UNITS=================
.Map("/getunits", units =>{ .Map("/getunits", units =>{
units.Run(async runner=>{ units.Run(async runner=>
if (!await RequestValidated(runner,2)) return; {
await WriteJsonResponse(runner,StatusCodes.Status200OK,"Success",Deployments); if (!await runner.RequestValidated(2)) return;
await runner.WriteJsonResponse( StatusCodes.Status200OK, "Success", Deployments);
}); });
}) })
.Map("/chunit", unit =>{ .Map("/chunit", unit =>{
unit.Run(async runner=>{ unit.Run(async runner=>{
if (!await RequestValidated(runner, 2, "POST", true)) return; if (!await runner.RequestValidated(2, "POST", true)) return;
if(await TryGetBodyJsonAsync(runner, ["deplid", "unitkerja"], CTS.Token) is Dictionary<string, JsonElement> InElement) if(await runner.TryGetBodyJsonAsync(["deplid", "unitkerja"], CTS.Token) is Dictionary<string, JsonElement> InElement)
{ {
Deployment CorrectDeployment = new( Deployment CorrectDeployment = new(
InElement["deplid"].GetInt16(), InElement["deplid"].GetInt16(),
@ -33,13 +34,13 @@ public static partial class APIHandler
); );
if (CorrectDeployment.UnitKerja.Length < 1) if (CorrectDeployment.UnitKerja.Length < 1)
{ {
await WriteJsonResponse(runner,StatusCodes.Status400BadRequest, "Unit Kerja can't be empty string."); await runner.WriteJsonResponse(StatusCodes.Status400BadRequest, "Unit Kerja can't be empty string.");
return; return;
} }
int i = Deployments.FindIndex(depl=>depl.DeplID == CorrectDeployment.DeplID); int i = Deployments.FindIndex(depl=>depl.DeplID == CorrectDeployment.DeplID);
if(i<0) if(i<0)
{ {
await WriteJsonResponse(runner,StatusCodes.Status404NotFound,"Deployment ID not found."); await runner.WriteJsonResponse(StatusCodes.Status404NotFound,"Deployment ID not found.");
return; return;
} }
_ = await RunNonQueryAsync(CS,"UPDATE deployment SET unitkerja = @uk WHERE deplid = @id",Comm=>{ _ = await RunNonQueryAsync(CS,"UPDATE deployment SET unitkerja = @uk WHERE deplid = @id",Comm=>{
@ -47,19 +48,19 @@ public static partial class APIHandler
Comm.Parameters.AddWithValue("@uk", CorrectDeployment.UnitKerja); Comm.Parameters.AddWithValue("@uk", CorrectDeployment.UnitKerja);
},CTS.Token); },CTS.Token);
Deployments[i] = CorrectDeployment; Deployments[i] = CorrectDeployment;
await WriteJsonResponse(runner,StatusCodes.Status202Accepted,"Data updated.",Deployments[i]); await runner.WriteJsonResponse(StatusCodes.Status202Accepted,"Data updated.",Deployments[i]);
} }
}); });
}) })
.Map("/addunit", unit =>{ .Map("/addunit", unit =>{
unit.Run(async runner=>{ unit.Run(async runner=>{
if (!await RequestValidated(runner, 2, "POST", true)) return; if (!await runner.RequestValidated(2, "POST", true)) return;
if(await TryGetBodyJsonAsync(runner, ["unitkerja"], CTS.Token) is Dictionary<string, JsonElement> InElement) if(await runner.TryGetBodyJsonAsync(["unitkerja"], CTS.Token) is Dictionary<string, JsonElement> InElement)
{ {
string UnitKerja = InElement["unitkerja"].GetString() ?? ""; string UnitKerja = InElement["unitkerja"].GetString() ?? "";
if (UnitKerja.Length < 1) if (UnitKerja.Length < 1)
{ {
await WriteJsonResponse(runner,StatusCodes.Status400BadRequest, "Unit Kerja can't be empty string."); await runner.WriteJsonResponse(StatusCodes.Status400BadRequest, "Unit Kerja can't be empty string.");
return; return;
} }
short DeplID = (short)await RunScalarAsync(CS,"INSERT INTO deployment OUTPUT INSERTED.deplid VALUES (@uk)",Comm=>{ short DeplID = (short)await RunScalarAsync(CS,"INSERT INTO deployment OUTPUT INSERTED.deplid VALUES (@uk)",Comm=>{
@ -68,30 +69,30 @@ public static partial class APIHandler
Deployment Inserted = new(DeplID,UnitKerja); Deployment Inserted = new(DeplID,UnitKerja);
Deployments.Add(Inserted); Deployments.Add(Inserted);
// EventsMarker.CacheUpdates = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString("X"); // EventsMarker.CacheUpdates = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString("X");
await WriteJsonResponse(runner,StatusCodes.Status201Created,"Data Created.",Inserted); await runner.WriteJsonResponse(StatusCodes.Status201Created,"Data Created.",Inserted);
} }
}); });
}) })
//============AGENTS============== //============AGENTS==============
.Map("/getagents", agents=>{ .Map("/getagents", agents=>{
agents.Run(async runner=>{ agents.Run(async runner=>{
if (!await RequestValidated(runner,2)) return; if (!await runner.RequestValidated(2)) return;
await WriteJsonResponse(runner,StatusCodes.Status200OK,"Success",Agents); await runner.WriteJsonResponse(StatusCodes.Status200OK,"Success",Agents);
}); });
}) })
.Map("/addagent", agent=>{ .Map("/addagent", agent=>{
agent.Run(async runner=>{ agent.Run(async runner=>{
if (!await RequestValidated(runner, 1, "POST", true)) return; if (!await runner.RequestValidated(1, "POST", true)) return;
if (await TryGetBodyJsonAsync(runner, ["agentid", "name", "jabatan", "deplid", "skangkat", "tmt", "skper", "tgper", "vision", "mission", "photo", "createuser", "uname", "pass", "level"], CTS.Token) is Dictionary<string, JsonElement> InElement) if (await runner.TryGetBodyJsonAsync(["agentid", "name", "jabatan", "deplid", "skangkat", "tmt", "skper", "tgper", "vision", "mission", "photo", "createuser", "uname", "pass", "level"], CTS.Token) is Dictionary<string, JsonElement> InElement)
{ {
string AgentID = InElement["agentid"].GetString() ?? string.Empty; string AgentID = InElement["agentid"].GetString() ?? string.Empty;
string Name = InElement["nama"].GetString() ?? string.Empty; string Name = InElement["name"].GetString() ?? string.Empty;
string Jabatan = InElement["jabatan"].GetString() ?? string.Empty; string Jabatan = InElement["jabatan"].GetString() ?? string.Empty;
short DeploymentID = InElement["deplid"].GetInt16(); short DeploymentID = InElement["deplid"].GetInt16();
string SKAngkat = InElement["skangkat"].GetString() ?? string.Empty; string SKAngkat = InElement["skangkat"].GetString() ?? string.Empty;
DateTime TMT = DateTime.Parse(InElement["tmt"].GetString() ?? "1970-01-01"); DateOnly TMT = DateOnly.Parse(InElement["tmt"].GetString()?[..10] ?? "1970-01-01");
string SKPer = InElement["skper"].GetString() ?? string.Empty; string SKPer = InElement["skper"].GetString() ?? string.Empty;
DateTime? TGPer = InElement["tgper"].GetString()?.Length > 0 ? DateTime.Parse(InElement["tgper"].GetString()!) : null; DateOnly? TGPer = InElement["tgper"].GetString()?.Length > 0 ? DateOnly.Parse(InElement["tgper"].GetString()![..10]) : null;
string Vision = InElement["vision"].GetString() ?? "-"; string Vision = InElement["vision"].GetString() ?? "-";
string Mission = InElement["mission"].GetString() ?? "-"; string Mission = InElement["mission"].GetString() ?? "-";
string Photo = InElement["photo"].GetString() ?? string.Empty; string Photo = InElement["photo"].GetString() ?? string.Empty;
@ -111,9 +112,10 @@ public static partial class APIHandler
(CreateUser && UName.Equals(string.Empty)) || (CreateUser && UName.Equals(string.Empty)) ||
(CreateUser && PlainPass.Equals(string.Empty)) || (CreateUser && PlainPass.Equals(string.Empty)) ||
(!Photo.Equals(string.Empty) && !PhotoMatch.Success) || (!Photo.Equals(string.Empty) && !PhotoMatch.Success) ||
(await RequestValidated(runner, Level, "POST"))) (!await runner.RequestValidated(Level, "POST"))
)
{ {
await WriteJsonResponse(runner, StatusCodes.Status400BadRequest, "One or more input(s) are not acceptable, in an unsupported format, or an attempt to create user account of a higher level than the creator is made."); await runner.WriteJsonResponse( StatusCodes.Status400BadRequest, "One or more input(s) are not acceptable, in an unsupported format, or an attempt to create user account of a higher level than the creator is made.");
return; return;
} }
if (!Photo.Equals(string.Empty)) if (!Photo.Equals(string.Empty))
@ -127,12 +129,13 @@ public static partial class APIHandler
if (!File.Exists(PhotoPath)) await File.WriteAllBytesAsync(PhotoPath, ImageBytes, CTS.Token); if (!File.Exists(PhotoPath)) await File.WriteAllBytesAsync(PhotoPath, ImageBytes, CTS.Token);
PhotoURL = Path.Combine("/assets/images/uploads", PhotoFileName); PhotoURL = Path.Combine("/assets/images/uploads", PhotoFileName);
} }
Agent NewAgent = new(AgentID, Name, Jabatan, DeploymentID, SKAngkat, TMT, SKPer.Length == 0 ? null : SKPer, SKPer.Length == 0 ? null : TGPer, Vision, Mission, Photo.Length == 0 ? null : PhotoURL);
await RunTransactionAsync(CS, async (Conn, Trans) => await RunTransactionAsync(CS, async (Conn, Trans) =>
{ {
using (SqlCommand CreateAgent = Conn.CreateCommand()) using (SqlCommand CreateAgent = Conn.CreateCommand())
{ {
CreateAgent.Transaction = Trans; CreateAgent.Transaction = Trans;
CreateAgent.CommandText = "INSERT INTO agents VALUE(@agid, @nama, @jabt, @deid, @skng, @tmt, @skpr, @tmpr, @visi, @misi, @poto)"; CreateAgent.CommandText = "INSERT INTO agents VALUES(@agid, @nama, @jabt, @deid, @skng, @tmt, @skpr, @tmpr, @visi, @misi, @poto)";
CreateAgent.Parameters.AddWithValue("@agid", AgentID); CreateAgent.Parameters.AddWithValue("@agid", AgentID);
CreateAgent.Parameters.AddWithValue("@nama", Name); CreateAgent.Parameters.AddWithValue("@nama", Name);
CreateAgent.Parameters.AddWithValue("@jabt", Jabatan); CreateAgent.Parameters.AddWithValue("@jabt", Jabatan);
@ -163,7 +166,8 @@ public static partial class APIHandler
}, CTS.Token }, CTS.Token
); );
string OutMessage = CreateUser ? "New Agent and respective User Account created" : "New Agent created. User account creation is possible."; string OutMessage = CreateUser ? "New Agent and respective User Account created" : "New Agent created. User account creation is possible.";
await WriteJsonResponse(runner, StatusCodes.Status201Created, OutMessage); await runner.WriteJsonResponse(StatusCodes.Status201Created, OutMessage, CreateUser?new SafeUser(UName,AgentID,Level,true):NewAgent);
// await runner.WriteJsonResponse(200, "OK", NewAgent);
} }
}); });
}) })