2020-05-17 20:01:30 +02:00
|
|
|
import Vapor
|
2022-05-22 23:24:04 +02:00
|
|
|
import Foundation
|
2020-05-17 20:01:30 +02:00
|
|
|
|
2021-11-08 21:58:55 +01:00
|
|
|
|
|
|
|
private(set) var server: CapServer!
|
|
|
|
|
2020-09-20 11:36:35 +02:00
|
|
|
public func configure(_ app: Application) throws {
|
2020-09-20 12:36:10 +02:00
|
|
|
|
|
|
|
app.http.server.configuration.port = 6001
|
2021-01-09 17:30:00 +01:00
|
|
|
app.routes.defaultMaxBodySize = "2mb"
|
2022-05-22 23:24:04 +02:00
|
|
|
|
2021-11-08 21:58:55 +01:00
|
|
|
let configFile = URL(fileURLWithPath: app.directory.resourcesDirectory)
|
2022-05-22 23:24:04 +02:00
|
|
|
.appendingPathComponent("config.json")
|
|
|
|
let config: Config
|
|
|
|
if !FileManager.default.fileExists(atPath: configFile.path) {
|
2022-10-07 21:13:21 +02:00
|
|
|
config = try writeDefaultCofig(to: configFile)
|
2022-05-22 23:24:04 +02:00
|
|
|
} else {
|
2022-10-07 21:13:21 +02:00
|
|
|
config = try loadConfig(at: configFile)
|
2021-11-08 21:58:55 +01:00
|
|
|
}
|
2022-05-22 23:24:04 +02:00
|
|
|
|
|
|
|
try Log.set(logFile: config.logPath)
|
|
|
|
|
|
|
|
let publicDirectory = app.directory.publicDirectory
|
|
|
|
if config.serveFiles {
|
|
|
|
let middleware = FileMiddleware(publicDirectory: publicDirectory)
|
|
|
|
app.middleware.use(middleware)
|
|
|
|
}
|
|
|
|
|
2022-05-27 09:25:41 +02:00
|
|
|
server = try CapServer(in: URL(fileURLWithPath: publicDirectory),
|
|
|
|
writers: config.writers)
|
2021-11-08 21:58:55 +01:00
|
|
|
|
2020-05-17 20:01:30 +02:00
|
|
|
// Register routes to the router
|
2020-09-20 11:36:35 +02:00
|
|
|
try routes(app)
|
2020-05-17 20:01:30 +02:00
|
|
|
}
|
2022-10-07 21:13:21 +02:00
|
|
|
|
|
|
|
private func writeDefaultCofig(to path: URL) throws -> Config {
|
|
|
|
do {
|
|
|
|
let configData = try JSONEncoder().encode(Config.default)
|
|
|
|
try configData.write(to: path)
|
|
|
|
print("Wrote default configuration to \(path.path)")
|
|
|
|
return .default
|
|
|
|
} catch {
|
|
|
|
print("Failed to write default config file at \(path.path): \(error)")
|
|
|
|
throw error
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private func loadConfig(at path: URL) throws -> Config {
|
|
|
|
do {
|
|
|
|
let configData = try Data(contentsOf: path)
|
|
|
|
return try JSONDecoder().decode(Config.self, from: configData)
|
|
|
|
} catch {
|
|
|
|
print("Failed to load config file at \(path.path): \(error)")
|
|
|
|
throw error
|
|
|
|
}
|
|
|
|
}
|