Do the thing ;-)

This commit is contained in:
Gender Shrapnel 2024-02-05 21:33:40 +01:00
parent be931262c2
commit 00f91888f7
Signed by: modzero
SSH Key Fingerprint: SHA256:hsF2onMcqHsX09jLIFn7GvltdH9NTfFd/1tCnBNfQ4g
11 changed files with 5555 additions and 109 deletions

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
@ -11,6 +11,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.1" />
<PackageReference Include="Microsoft.AspNetCore.SpaProxy"> <PackageReference Include="Microsoft.AspNetCore.SpaProxy">
<Version>8.*-*</Version> <Version>8.*-*</Version>
</PackageReference> </PackageReference>

View File

@ -1,6 +1,6 @@
@AdverCalculator.Server_HostAddress = http://localhost:5129 @AdverCalculator.Server_HostAddress = http://localhost:5129
GET {{AdverCalculator.Server_HostAddress}}/weatherforecast/ GET {{AdverCalculator.Server_HostAddress}}/add
Accept: application/json Accept: application/json
### ###

View File

@ -0,0 +1,12 @@
namespace AdverCalculator.Server;
public static class CalculatorEndpoints
{
public static void Map(WebApplication app)
{
app.MapGet("/add", (double left, double right) => Task.FromResult(left + right)).WithName("Add").WithOpenApi();
app.MapGet("/subtract", (double left, double right) => Task.FromResult(left - right)).WithName("Subtract").WithOpenApi();
app.MapGet("/multiply", (double left, double right) => Task.FromResult(left * right)).WithName("Multiply").WithOpenApi();
app.MapGet("/divide", (double left, double right) => Task.FromResult(left / right)).WithName("Divide").WithOpenApi();
}
}

View File

@ -1,33 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace AdverCalculator.Server.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}

View File

@ -1,9 +1,7 @@
using AdverCalculator.Server;
var builder = WebApplication.CreateBuilder(args); 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.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
@ -12,6 +10,7 @@ var app = builder.Build();
app.UseDefaultFiles(); app.UseDefaultFiles();
app.UseStaticFiles(); app.UseStaticFiles();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {
@ -21,9 +20,7 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseAuthorization(); CalculatorEndpoints.Map(app);
app.MapControllers();
app.MapFallbackToFile("/index.html"); app.MapFallbackToFile("/index.html");

View File

@ -1,13 +0,0 @@
namespace AdverCalculator.Server
{
public class WeatherForecast
{
public DateOnly Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
}

View File

@ -4,6 +4,16 @@ A web calculator with a .NET backend and a React front-end, an evaluation assign
Details of the requirement conversation are on the bottom. Details of the requirement conversation are on the bottom.
## Running
```sh
$ dotnet run --project .\AdverCalculator.Server\ -lp https
```
This will start an API server and bring up the React app. The app uses a Vite
host, including an API proxy - unfortunately the current configuration only
works with the https profile.
## Evaluation ## Evaluation
Documenting the process: for a greenfield project, or anything that feels Documenting the process: for a greenfield project, or anything that feels
@ -89,7 +99,7 @@ Furthermore the calculator state will contain three variables:
#### Operator Pressed in `After Equals` or `After Operator` #### Operator Pressed in `After Equals` or `After Operator`
- `Current Operator` is set to the selected operator. - `Current Operator` is set to the selected operator.
- `Right Operand` is set to `Left Operand`. - `Left Operand` is set to `Right Operand`.
- We progress to the `After Operator` state. - We progress to the `After Operator` state.
This means that, for example, the sequence `12 * 3 = - =` will give `0`: This means that, for example, the sequence `12 * 3 = - =` will give `0`:
@ -102,7 +112,7 @@ This means that, for example, the sequence `12 * 3 = - =` will give `0`:
- Lock the UI. - Lock the UI.
- `Current Operator` is set to the selected operator. - `Current Operator` is set to the selected operator.
- Evaluate the operation of `Left Operand [Current Operator] Right Operand`. - Evaluate the operation of `Left Operand [Current Operator] Right Operand`.
- `Left Operator` is set to the operation's result. - `Left Operand` is set to the operation's result.
- Unlock the UI. - Unlock the UI.
- Progress to `After Operator`. - Progress to `After Operator`.
@ -112,7 +122,7 @@ Note that the right operand remains untouched.
- Lock the UI. - Lock the UI.
- Evaluate the operation of `Left Operand [Current Operator] Right Operand`. - Evaluate the operation of `Left Operand [Current Operator] Right Operand`.
- `Left Operator` is set to the operation's result. - `Left Operand` is set to the operation's result.
- Unlock the UI. - Unlock the UI.
- Progress to `After Equals`. - Progress to `After Equals`.
@ -120,7 +130,7 @@ Note that both `Right Operand` and `Current Operator` remain untouched.
Repeatedly pressing `=` will result in repeating the operation multiple times, Repeatedly pressing `=` will result in repeating the operation multiple times,
like `12*3*3*3`. like `12*3*3*3`.
#### Digit Pressed in `After Equals` or `After Digit` #### Digit Pressed in `After Equals` or `After Operator`
- `Right Operand` is replaced with the digit. - `Right Operand` is replaced with the digit.
- We progress to `After Digit`. - We progress to `After Digit`.

5389
advercalculator.client/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -6,11 +6,11 @@
} }
tr:nth-child(even) { tr:nth-child(even) {
background: #F2F2F2; /* background: #F2F2F2;*/
} }
tr:nth-child(odd) { tr:nth-child(odd) {
background: #FFF; /* background: #FFF;*/
} }
th, td { th, td {

View File

@ -1,56 +1,139 @@
import { useEffect, useState } from 'react'; import { useState } from 'react';
import './App.css'; import './App.css';
interface Forecast { const OOperator = {
date: string; Addition: "add",
temperatureC: number; Subtraction: "subtract",
temperatureF: number; Multiplication: "multiply",
summary: string; Division: "divide",
} as const;
type Operator = typeof OOperator[keyof typeof OOperator];
enum CalculatorState {
AFTER_EQUALS,
AFTER_OPERATOR,
AFTER_DIGIT,
}
interface Calculator {
readonly leftOperand: string;
readonly rightOperand: string;
readonly operator?: Operator;
readonly state: CalculatorState;
}
function makeCalculator(): Calculator {
return {
leftOperand: "0",
rightOperand: "0",
operator: undefined,
state: CalculatorState.AFTER_EQUALS
}
}
async function evaluate(c: Calculator) {
if (c.operator === undefined) {
return c.rightOperand;
}
return await fetch(c.operator.toString() + "?" + new URLSearchParams({
left: c.leftOperand,
right: c.rightOperand,
})).then(r => r.text());
}
async function operator(c: Calculator, op: Operator): Promise<Calculator> {
switch (c.state) {
case CalculatorState.AFTER_EQUALS:
case CalculatorState.AFTER_OPERATOR:
return {
...c,
leftOperand: c.rightOperand,
operator: op,
state: CalculatorState.AFTER_OPERATOR,
}
case CalculatorState.AFTER_DIGIT:
const result = await evaluate(c);
return {
...c,
operator: op,
leftOperand: result,
state: CalculatorState.AFTER_OPERATOR,
}
}
}
async function digit(c: Calculator, digit: string): Promise<Calculator> {
switch (c.state) {
case CalculatorState.AFTER_EQUALS:
case CalculatorState.AFTER_OPERATOR:
return {
...c,
leftOperand: c.rightOperand,
rightOperand: digit,
state: CalculatorState.AFTER_DIGIT,
}
case CalculatorState.AFTER_DIGIT:
return {
...c,
rightOperand: c.rightOperand + digit,
}
}
}
async function equals(c: Calculator): Promise<Calculator> {
return {
...c,
leftOperand: await evaluate(c),
state: CalculatorState.AFTER_EQUALS,
}
} }
function App() { function App() {
const [forecasts, setForecasts] = useState<Forecast[]>(); const [calculator, setCalculator] = useState<Calculator>(makeCalculator());
const [uiEnabled, setUiEnabled] = useState<boolean>(true);
useEffect(() => { async function operatorClicked(op: Operator) {
populateWeatherData(); setUiEnabled(false);
}, []); setCalculator(await operator(calculator, op));
setUiEnabled(true);
}
const contents = forecasts === undefined async function digitClicked(d: number) {
? <p><em>Loading... Please refresh once the ASP.NET backend has started. See <a href="https://aka.ms/jspsintegrationreact">https://aka.ms/jspsintegrationreact</a> for more details.</em></p> setUiEnabled(false);
: <table className="table table-striped" aria-labelledby="tabelLabel"> setCalculator(await digit(calculator, d.toString()));
<thead> setUiEnabled(true);
<tr> }
<th>Date</th>
<th>Temp. (C)</th> async function equalsClicked() {
<th>Temp. (F)</th> setUiEnabled(false);
<th>Summary</th> setCalculator(await equals(calculator));
</tr> setUiEnabled(true);
</thead> }
<tbody>
{forecasts.map(forecast =>
<tr key={forecast.date}>
<td>{forecast.date}</td>
<td>{forecast.temperatureC}</td>
<td>{forecast.temperatureF}</td>
<td>{forecast.summary}</td>
</tr>
)}
</tbody>
</table>;
return ( return (
<div> <div>
<h1 id="tabelLabel">Weather forecast</h1> <div>{calculator.state == CalculatorState.AFTER_DIGIT ? calculator.rightOperand : calculator.leftOperand}</div>
<p>This component demonstrates fetching data from the server.</p> <div>
{contents} <button disabled={!uiEnabled} onClick={() => operatorClicked(OOperator.Addition)}>+</button>
<button disabled={!uiEnabled} onClick={() => operatorClicked(OOperator.Subtraction)}>-</button>
<button disabled={!uiEnabled} onClick={() => operatorClicked(OOperator.Multiplication)}>*</button>
<button disabled={!uiEnabled} onClick={() => operatorClicked(OOperator.Division)}>/</button>
<button disabled={!uiEnabled} onClick={() => equalsClicked()}>=</button>
</div>
<div>{
[1, 2, 3].map((r) => (
<div key={r}>{
[1, 2, 3].map((c) => (
<button key={r * c} disabled={!uiEnabled} onClick={() => digitClicked(r * c)}>{r * c}</button>
))
}</div>
))
}</div>
<div> <button disabled={!uiEnabled} onClick={() => digitClicked(0)}>0</button></div>
</div> </div>
); );
async function populateWeatherData() {
const response = await fetch('weatherforecast');
const data = await response.json();
setForecasts(data);
}
} }
export default App; export default App;

View File

@ -46,7 +46,7 @@ export default defineConfig({
}, },
server: { server: {
proxy: { proxy: {
'^/weatherforecast': { '^/(add|multiply|subtract|divide)': {
target: 'https://localhost:7102/', target: 'https://localhost:7102/',
secure: false secure: false
} }