Skip to content

Instantly share code, notes, and snippets.

@FantailIO
Created September 18, 2017 09:24
Show Gist options
  • Save FantailIO/949e793f96b69e8b1b0b34a9c6501e16 to your computer and use it in GitHub Desktop.
Save FantailIO/949e793f96b69e8b1b0b34a9c6501e16 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Timeapi.Data;
using Timeapi.Model;
using Timeapi.Utils;
namespace Timeapi.Controllers
{
[Route("api/time", Name = "TimeApi")]
[EnableCors("AllowAllOrigins")]
public class TimeController : Controller
{
private readonly TimeContext _timeCtx;
private readonly FeatureToggle _featureToggle;
public TimeController(TimeContext timeCtx, FeatureToggle featureToggle)
{
_timeCtx = timeCtx;
_featureToggle = featureToggle;
}
// GET api/time
[HttpGet]
public IEnumerable<TimeEntry> Get()
{
return _timeCtx.Times;
}
// GET api/time/5
[HttpGet("{id}", Name = "GetTimeById")]
public async Task<IActionResult> Get(string id)
{
var te = await _timeCtx.Times.FindAsync(id);
if (te != null)
{
return Ok(te);
}
else
{
return NotFound();
}
}
// POST api/time
[HttpPost]
public async Task<IActionResult> Post([FromBody]TimeEntry te)
{
if (te.ID != null || te.ProjectID == null || te.Hours <= 0.0 || te.Hours > 24)
{
return BadRequest();
}
if (!_featureToggle.checkToggle(FeatureName.TimesCreate))
{
return NotFound("There is no such feature, wink wink");
}
if (te.ProjectID == "INVALID")
{
return NotFound("A project with ID " + te.ProjectID + " was not found");
}
await _timeCtx.AddAsync(te);
await _timeCtx.SaveChangesAsync();
return CreatedAtRoute("GetTimeById", new { id = te.ID }, te);
}
// PUT api/time
[HttpPut("{id}")]
public async Task<IActionResult> Put(string id, [FromBody]TimeEntry te)
{
var oldTe = await _timeCtx.Times.FindAsync(id);
if (te == null)
{
return NotFound();
}
oldTe.ProjectID = te.ProjectID;
oldTe.Hours = te.Hours;
oldTe.Description = te.Description;
await _timeCtx.SaveChangesAsync();
return Ok();
}
// DELETE api/time/5
/// <summary>
/// Removes the time entry - for a very very long time
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(string id)
{
if (!_featureToggle.checkToggle(FeatureName.TimesDelete))
{
return NotFound("There is no such feature, wink wink");
}
var te = await _timeCtx.Times.FindAsync(id);
_timeCtx.Times.Remove(te);
await _timeCtx.SaveChangesAsync();
return Ok();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment