BackEnd/YTManager/Controllers/Channels.cs

55 lines
1.8 KiB
C#

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace YTManager.Controllers {
[Produces("application/json")]
[Route("api/Channels")]
public class ChannelsController : Controller {
// Custom return type for API accesses. Done this way to ensure we
// always return the expected data regardless of the underlying model.
struct Channel_ForAPI {
public string Title;
public string Description;
public string ID;
public List<string> Video_IDs;
public Channel_ForAPI(Models.Channel c) {
Title = c.Title;
Description = c.Description;
ID = c.YoutubeID;
Video_IDs = c.Videos?.Select(v => v.YoutubeID).ToList();
}
}
// DB context used for all these calls.
private readonly MediaDB db;
// Maximum number of channels to return per query.
private readonly int max_per_query = 20;
// Constructor to fetch the db context.
public ChannelsController(MediaDB context) => db = context;
// Returns the most recently added channels.
[HttpGet]
public async Task<IActionResult> Get() {
// Get all the relevant channels.
var chanels = await db.Channels
.OrderByDescending(i => i.AddedtoDB)
.Take(max_per_query)
.ToListAsync();
// Convert them to what we will send out.
var converted = chanels
.Select(ch => new Channel_ForAPI(ch))
.ToList();
// Convert all the videos to what we will send back.
return Ok(converted);
}
}
}