~jpgleeson/caint

ref: 9a6a9c60830adc2f934ec3f8ac1676e0c939a48f caint/Controllers/ThreadsController.cs -rw-r--r-- 2.4 KiB
9a6a9c60 — jpgleeson Set to local rather than live 1 year, 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using Microsoft.EntityFrameworkCore;
using caint.Data;
using caint.Models;

namespace caint.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ThreadsController : ControllerBase
    {
        private readonly caintDBContext _context;

        public ThreadsController(caintDBContext context)
        {
            _context = context;
        }

        [HttpOptions]
        public IActionResult PreflightRoute()
        {
            Console.WriteLine("preflight");
            return NoContent();
        }

        // GET: api/threads
        [EnableCors]
        [HttpGet]
        public async Task<ActionResult<IEnumerable<ThreadDTO>>> GetThread(string hostname, string pathname)
        {
            return await _context.threads.Select(x => ItemToDTO(x)).ToListAsync();
        }

        // GET: api/threads/5
        [EnableCors]
        [HttpGet("{id}")]
        public async Task<ActionResult<ThreadDTO>> GetComment(long id)
        {
            var thread = await _context.threads.FindAsync(id);

            if (thread == null)
            {
                return NotFound();
            }

            return ItemToDTO(thread);
        }

        // POST: api/threads
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [EnableCors]
        [HttpPost]
        public async Task<long> NewThread(NewThreadDTO newThread)
        {
            var _threads = await _context.threads.ToListAsync();

            foreach (Thread eachThread in _threads)
            {
                
                if (eachThread.hostname == newThread.hostname && eachThread.path == newThread.path)
                {
                    return (eachThread.id);
                }
            }

            var thread = new Thread{
                hostname = newThread.hostname,
                path = newThread.path
            };
            
            _context.threads.Add(thread);
            await _context.SaveChangesAsync();

            return (ItemToDTO(thread).id);
        }

        private static ThreadDTO ItemToDTO(Thread thread) =>
        new ThreadDTO 
        {
            id = thread.id
        };

    }
}