Everywhere: Create basic test page
This commit is contained in:
@@ -5,11 +5,14 @@ struct TodoController: RouteCollection {
|
||||
func boot(routes: RoutesBuilder) throws {
|
||||
let todos = routes.grouped("todos")
|
||||
|
||||
todos.get(use: self.index)
|
||||
todos.post(use: self.create)
|
||||
todos.group(":todoID") { todo in
|
||||
todo.delete(use: self.delete)
|
||||
todos.get(use: index)
|
||||
todos.post(use: create)
|
||||
todos.group(":id") { todo in
|
||||
todo.get(use: show)
|
||||
todo.put(use: update)
|
||||
todo.delete(use: delete)
|
||||
}
|
||||
// todos.delete(":todoID", use: delete)
|
||||
}
|
||||
|
||||
@Sendable
|
||||
@@ -17,21 +20,63 @@ struct TodoController: RouteCollection {
|
||||
try await Todo.query(on: req.db).all().map { $0.toDTO() }
|
||||
}
|
||||
|
||||
@Sendable
|
||||
func show(req: Request) async throws -> TodoDTO {
|
||||
guard let uuid = hexToUUID(hex: req.parameters.get("id")!),
|
||||
let todo = try await Todo.find(uuid, on: req.db) else {
|
||||
throw Abort(.notFound)
|
||||
}
|
||||
|
||||
return todo.toDTO()
|
||||
}
|
||||
|
||||
@Sendable
|
||||
func create(req: Request) async throws -> TodoDTO {
|
||||
let todo = try req.content.decode(TodoDTO.self).toModel()
|
||||
|
||||
try await todo.save(on: req.db)
|
||||
|
||||
return todo.toDTO()
|
||||
}
|
||||
|
||||
@Sendable
|
||||
func update(req: Request) async throws -> TodoDTO {
|
||||
guard let uuid = hexToUUID(hex: req.parameters.get("id")!),
|
||||
let todo = try await Todo.find(uuid, on: req.db) else {
|
||||
throw Abort(.notFound)
|
||||
}
|
||||
|
||||
let updatedTodo = try req.content.decode(Todo.self)
|
||||
todo.title = updatedTodo.title
|
||||
try await todo.save(on: req.db)
|
||||
|
||||
return todo.toDTO()
|
||||
}
|
||||
|
||||
@Sendable
|
||||
func delete(req: Request) async throws -> HTTPStatus {
|
||||
guard let todo = try await Todo.find(req.parameters.get("todoID"), on: req.db) else {
|
||||
guard let uuid = hexToUUID(hex: req.parameters.get("id")!),
|
||||
let todo = try await Todo.find(uuid, on: req.db) else {
|
||||
throw Abort(.notFound)
|
||||
}
|
||||
|
||||
try await todo.delete(on: req.db)
|
||||
|
||||
return .noContent
|
||||
}
|
||||
|
||||
// -------------------------------------
|
||||
|
||||
private func hexToUUID(hex: String) -> UUID? {
|
||||
var uuid: String = hex.replacingOccurrences(of: "-", with: "")
|
||||
|
||||
guard uuid.count == 32 else { return nil }
|
||||
|
||||
uuid.insert("-", at: uuid.index(uuid.startIndex, offsetBy: 8))
|
||||
uuid.insert("-", at: uuid.index(uuid.startIndex, offsetBy: 12 + 1))
|
||||
uuid.insert("-", at: uuid.index(uuid.startIndex, offsetBy: 16 + 2))
|
||||
uuid.insert("-", at: uuid.index(uuid.startIndex, offsetBy: 20 + 3))
|
||||
|
||||
return UUID(uuidString: uuid)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import Vapor
|
||||
|
||||
// Modified from Vapor.ErrorMiddleware
|
||||
|
||||
public final class CustomErrorMiddleware: Middleware {
|
||||
// Default response
|
||||
public struct ErrorResponse: Codable {
|
||||
var error: Bool
|
||||
var reason: String
|
||||
}
|
||||
|
||||
public init(environment: Environment) {
|
||||
self.environment = environment
|
||||
}
|
||||
|
||||
public func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
|
||||
next.respond(to: request).flatMapErrorThrowing { error in
|
||||
self.makeResponse(with: request, reason: error)
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------
|
||||
|
||||
private func makeResponse(with req: Request, reason error: Error) -> Response {
|
||||
let reason: String
|
||||
let status: HTTPResponseStatus
|
||||
var headers: HTTPHeaders
|
||||
let source: ErrorSource
|
||||
|
||||
// Inspect the error type and extract what data we can.
|
||||
switch error {
|
||||
case let debugAbort as (DebuggableError & AbortError):
|
||||
(reason, status, headers, source) = (debugAbort.reason, debugAbort.status, debugAbort.headers, debugAbort.source ?? .capture())
|
||||
|
||||
case let abort as AbortError:
|
||||
(reason, status, headers, source) = (abort.reason, abort.status, abort.headers, .capture())
|
||||
|
||||
case let debugErr as DebuggableError:
|
||||
(reason, status, headers, source) = (debugErr.reason, .internalServerError, [:], debugErr.source ?? .capture())
|
||||
|
||||
default:
|
||||
// In debug mode, provide the error description; otherwise hide it to avoid sensitive data disclosure.
|
||||
reason = environment.isRelease ? "Something went wrong." : String(describing: error)
|
||||
(status, headers, source) = (.internalServerError, [:], .capture())
|
||||
}
|
||||
|
||||
// Report the error
|
||||
req.logger.report(error: error, file: source.file, function: source.function, line: source.line)
|
||||
|
||||
let body = makeResponseBody(with: req, reason: reason, status: status, headers: &headers)
|
||||
|
||||
// Create a Response with appropriate status
|
||||
return Response(status: status, headers: headers, body: body)
|
||||
}
|
||||
|
||||
private func makeResponseBody(with req: Request, reason: String, status: HTTPResponseStatus,
|
||||
headers: inout HTTPHeaders) -> Response.Body {
|
||||
let body: Response.Body
|
||||
|
||||
if let acceptHeader = req.headers.first(name: "Accept"),
|
||||
acceptHeader == "application/json" {
|
||||
// Attempt to serialize the error to JSON
|
||||
do {
|
||||
let encoder = try ContentConfiguration.global.requireEncoder(for: .json)
|
||||
var byteBuffer = req.byteBufferAllocator.buffer(capacity: 0)
|
||||
try encoder.encode(ErrorResponse(error: true, reason: reason), to: &byteBuffer, headers: &headers)
|
||||
|
||||
body = .init(
|
||||
buffer: byteBuffer,
|
||||
byteBufferAllocator: req.byteBufferAllocator
|
||||
)
|
||||
} catch {
|
||||
body = .init(string: "Oops: \(String(describing: error))\nWhile encoding error: \(reason)",
|
||||
byteBufferAllocator: req.byteBufferAllocator)
|
||||
headers.contentType = .plainText
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Attempt to render the error to a page
|
||||
let statusCode = String(status.code)
|
||||
body = .init(string: MainLayout(title: "Error \(statusCode))") {
|
||||
ErrorPage(status: statusCode, reason: reason)
|
||||
}.render())
|
||||
headers.contentType = .html
|
||||
}
|
||||
|
||||
return body
|
||||
}
|
||||
|
||||
private let environment: Environment
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import Elementary
|
||||
|
||||
struct ErrorPage: HTML {
|
||||
var status: String
|
||||
var reason: String
|
||||
|
||||
// -------------------------------------
|
||||
|
||||
var content: some HTML {
|
||||
div {
|
||||
p { "Error "; strong { status }; "." }
|
||||
p { reason }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import Elementary
|
||||
|
||||
struct IndexPage: HTML {
|
||||
var content: some HTML {
|
||||
h1 { "Welcome to Our Website" }
|
||||
p {
|
||||
"This is a basic Bootstrap page with a sticky navigation bar and content in the middle."
|
||||
}
|
||||
p { "The navigation bar will stay at the top of the page as you scroll down." }
|
||||
p {
|
||||
"""
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam tincidunt arcu
|
||||
sit amet leo rutrum luctus. Sed metus mi, consectetur vitae dui at, sodales
|
||||
dignissim odio. Curabitur a nisi eros. Suspendisse semper ac justo non gravida.
|
||||
Vestibulum accumsan interdum varius. Morbi at diam luctus, mattis mi nec, mollis
|
||||
libero. Pellentesque habitant morbi tristique senectus et netus et malesuada
|
||||
fames ac turpis egestas. Integer congue, nisl in tempus ultricies, ligula est
|
||||
laoreet elit, sed elementum erat dui ac nisl. Aenean pulvinar arcu eget urna
|
||||
venenatis, at dictum arcu ultrices. Etiam hendrerit, purus vitae sagittis
|
||||
lobortis, nisi sapien vestibulum arcu, ut mattis arcu elit ut arcu. Nulla vitae
|
||||
sem ac eros ullamcorper efficitur ut id arcu. Vestibulum euismod arcu eget
|
||||
aliquet tempor. Nullam nec consequat magna. Etiam posuere, ipsum id condimentum
|
||||
mollis, massa libero efficitur lectus, nec tempor mauris tellus ut ligula.
|
||||
Quisque viverra diam velit, quis ultricies nisl lacinia vitae.
|
||||
|
||||
Aliquam libero nibh, luctus vel augue at, congue feugiat risus. Mauris volutpat
|
||||
eget eros ac congue. Duis venenatis, arcu vel sodales accumsan, diam mi posuere
|
||||
mi, vitae rutrum ex mauris nec libero. Sed eleifend nulla magna, eu lobortis
|
||||
mauris fringilla nec. In posuere dignissim eros, ut hendrerit quam lacinia eu.
|
||||
Praesent vestibulum arcu enim, hendrerit convallis risus facilisis eu. Nunc
|
||||
vitae mauris eu nulla laoreet rhoncus. Nullam ligula tellus, vulputate in
|
||||
viverra nec, eleifend eu nulla. Praesent suscipit rutrum imperdiet.
|
||||
|
||||
Curabitur in lacus eu diam cursus viverra non eget turpis. Donec a ornare ipsum,
|
||||
sed egestas orci. Vivamus congue gravida elementum. Pellentesque vitae mauris
|
||||
magna. Phasellus blandit urna vitae auctor consectetur. Aenean iaculis eget arcu
|
||||
vitae ultricies. Nunc maximus, massa hendrerit faucibus fringilla, eros quam
|
||||
consequat enim, sit amet sodales erat quam eget massa.
|
||||
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum in venenatis
|
||||
urna. Vestibulum lectus arcu, scelerisque in ipsum vitae, feugiat cursus tortor.
|
||||
Maecenas aliquam nunc enim, id fringilla est mattis et. Vivamus vitae
|
||||
ullamcorper erat. Sed quis vehicula felis, quis bibendum nunc. Duis semper
|
||||
fermentum ante, id fermentum neque varius convallis. Donec dui leo, fringilla
|
||||
nec massa nec, fermentum molestie purus. Donec eget feugiat velit. Nulla
|
||||
facilisi. Cras maximus felis eu libero mollis consectetur. Nulla molestie vitae
|
||||
neque venenatis porta.
|
||||
|
||||
Vestibulum nunc diam, mattis eu bibendum at, sagittis vitae nunc. Duis lacinia
|
||||
sodales enim, et elementum libero posuere et. Donec ut fringilla orci. Donec at
|
||||
aliquet ipsum, quis mattis risus. Donec malesuada enim in egestas blandit. Proin
|
||||
sagittis mauris magna, elementum faucibus metus tempus eu. Sed in sem ut tellus
|
||||
porta luctus et sed diam. Donec felis ante, euismod a est vitae, mollis
|
||||
condimentum nulla.
|
||||
"""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import Elementary
|
||||
|
||||
extension MainLayout: Sendable where Body: Sendable {}
|
||||
struct MainLayout<Body: HTML>: HTMLDocument {
|
||||
var title: String
|
||||
@HTMLBuilder var pageContent: Body // This var name can't be changed!
|
||||
|
||||
// https://www.srihash.org/
|
||||
var head: some HTML {
|
||||
meta(.charset(.utf8))
|
||||
meta(.name(.viewport), .content("width=device-width, initial-scale=1.0"))
|
||||
|
||||
// ---------------------------------
|
||||
// CSS includes
|
||||
|
||||
link(
|
||||
.rel(.stylesheet),
|
||||
.href("https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css"),
|
||||
.integrity("sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"),
|
||||
.crossorigin(.anonymous))
|
||||
link(.rel(.stylesheet), .href("/style.css"))
|
||||
|
||||
style {
|
||||
"""
|
||||
body {
|
||||
padding-top: 56px;
|
||||
}
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
var body: some HTML {
|
||||
// ---------------------------------
|
||||
// Header
|
||||
|
||||
header {
|
||||
NavMenu()
|
||||
}
|
||||
|
||||
// ---------------------------------
|
||||
// Body
|
||||
|
||||
main {
|
||||
div(.class("cotainer mt-4")) {
|
||||
div(.class("content px-4 pb-4")) {
|
||||
pageContent
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------
|
||||
// JS includes
|
||||
|
||||
script(
|
||||
.src(
|
||||
"https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js"),
|
||||
.integrity("sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"),
|
||||
.crossorigin(.anonymous)
|
||||
) {}
|
||||
script(.src("/js/site.js")) {}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import Elementary
|
||||
|
||||
struct NavMenu: HTML {
|
||||
var content: some HTML {
|
||||
nav(.class("navbar navbar-expand-lg navbar-light bg-light fixed-top")) {
|
||||
div(.class("container-fluid")) {
|
||||
a(.class("navbar-brand"), .href("#")) { "Logo" }
|
||||
button(
|
||||
.class("navbar-toggler"), .type(.button),
|
||||
.data("bs-toggle", value: "collapse"),
|
||||
.data("bs-target", value: "#navbarNav")
|
||||
) {
|
||||
span(.class("navbar-toggler-icon")) {}
|
||||
}
|
||||
div(.class("collapse navbar-collapse"), .id("navbarNav")) {
|
||||
ul(.class("navbar-nav me-auto mb-2 mb-lg-0")) {
|
||||
li(.class("nav-item")) {
|
||||
a(.class("nav-link active"), .href("#")) { "Home" }
|
||||
}
|
||||
li(.class("nav-item")) {
|
||||
a(.class("nav-link"), .href("#")) { "About" }
|
||||
}
|
||||
li(.class("nav-item")) {
|
||||
a(.class("nav-link"), .href("#")) { "Services" }
|
||||
}
|
||||
li(.class("nav-item")) {
|
||||
a(.class("nav-link"), .href("#")) { "Contact" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,20 +3,34 @@ import Fluent
|
||||
import FluentMySQLDriver
|
||||
import Vapor
|
||||
|
||||
// configures your application
|
||||
// Configures your application
|
||||
public func configure(_ app: Application) async throws {
|
||||
// uncomment to serve files from /Public folder
|
||||
// app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
|
||||
app.middleware = .init()
|
||||
// Error HTML pages or JSON responses
|
||||
app.middleware.use(CustomErrorMiddleware(environment: app.environment))
|
||||
// Serve files from /Public folder
|
||||
app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
|
||||
|
||||
// sudo mariadb-install-db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
|
||||
// sudo systemctl enable mariadb.service
|
||||
// sudo systemctl start mariadb.service
|
||||
// sudo mariadb
|
||||
// > CREATE DATABASE riyyi;
|
||||
// > GRANT ALL ON riyyi.* TO 'riyyi'@'%' IDENTIFIED BY '123' WITH GRANT OPTION;
|
||||
// > GRANT ALL ON riyyi.* TO 'riyyi'@'localhost' IDENTIFIED BY '123' WITH GRANT OPTION; // % does NOT match localhost!
|
||||
// > FLUSH PRIVILEGES;
|
||||
|
||||
app.databases.use(DatabaseConfigurationFactory.mysql(
|
||||
hostname: Environment.get("DATABASE_HOST") ?? "localhost",
|
||||
port: Environment.get("DATABASE_PORT").flatMap(Int.init(_:)) ?? MySQLConfiguration.ianaPortNumber,
|
||||
username: Environment.get("DATABASE_USERNAME") ?? "vapor_username",
|
||||
password: Environment.get("DATABASE_PASSWORD") ?? "vapor_password",
|
||||
database: Environment.get("DATABASE_NAME") ?? "vapor_database"
|
||||
username: Environment.get("DATABASE_USERNAME") ?? "riyyi",
|
||||
password: Environment.get("DATABASE_PASSWORD") ?? "123",
|
||||
database: Environment.get("DATABASE_NAME") ?? "riyyi",
|
||||
tlsConfiguration: nil // Local connections dont need encryption
|
||||
), as: .mysql)
|
||||
|
||||
app.migrations.add(CreateTodo())
|
||||
// register routes
|
||||
|
||||
// Register routes
|
||||
try routes(app)
|
||||
}
|
||||
|
||||
@@ -8,16 +8,20 @@ enum Entrypoint {
|
||||
static func main() async throws {
|
||||
var env = try Environment.detect()
|
||||
try LoggingSystem.bootstrap(from: &env)
|
||||
|
||||
|
||||
let app = try await Application.make(env)
|
||||
|
||||
#if DEBUG
|
||||
app.logger.logLevel = .debug
|
||||
#endif
|
||||
|
||||
// This attempts to install NIO as the Swift Concurrency global executor.
|
||||
// You can enable it if you'd like to reduce the amount of context switching between NIO and Swift Concurrency.
|
||||
// Note: this has caused issues with some libraries that use `.wait()` and cleanly shutting down.
|
||||
// If enabled, you should be careful about calling async functions before this point as it can cause assertion failures.
|
||||
// let executorTakeoverSuccess = NIOSingletons.unsafeTryInstallSingletonPosixEventLoopGroupAsConcurrencyGlobalExecutor()
|
||||
// app.logger.debug("Tried to install SwiftNIO's EventLoopGroup as Swift's global concurrency executor", metadata: ["success": .stringConvertible(executorTakeoverSuccess)])
|
||||
|
||||
|
||||
do {
|
||||
try await configure(app)
|
||||
} catch {
|
||||
@@ -25,6 +29,7 @@ enum Entrypoint {
|
||||
try? await app.asyncShutdown()
|
||||
throw error
|
||||
}
|
||||
|
||||
try await app.execute()
|
||||
try await app.asyncShutdown()
|
||||
}
|
||||
|
||||
@@ -1,14 +1,41 @@
|
||||
import Elementary
|
||||
import Fluent
|
||||
import Vapor
|
||||
import VaporElementary
|
||||
|
||||
func routes(_ app: Application) throws {
|
||||
app.get { req async in
|
||||
"It works!"
|
||||
app.routes.caseInsensitive = true
|
||||
|
||||
app.get { req async throws in
|
||||
|
||||
let todo = Todo(title: "Test Todo")
|
||||
try await todo.save(on: req.db)
|
||||
|
||||
return "It works!"
|
||||
}
|
||||
|
||||
app.get("hello") { req async -> String in
|
||||
"Hello, world!"
|
||||
}
|
||||
|
||||
app.get("test") { _ in
|
||||
HTMLResponse {
|
||||
MainLayout(title: "Test123") {
|
||||
IndexPage()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try app.register(collection: TodoController())
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
Closure Expression Syntax
|
||||
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/closures#Closure-Expression-Syntax
|
||||
|
||||
{ (<#parameters#>) -> <#return type#> in
|
||||
<#statements#>
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user