Skip to content

Commit

Permalink
Merge pull request #39 from cocoaheadsru/task/devops/generate-test-da…
Browse files Browse the repository at this point in the history
…taset

Pre-release PR (changed endpoints, created stage samples, refactored photo, VK - issues solved)
  • Loading branch information
ditansu authored Mar 11, 2018
2 parents 5602805 + a4f3456 commit 3367dbf
Show file tree
Hide file tree
Showing 70 changed files with 918 additions and 308 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ DerivedData/
# End of https://www.gitignore.io/api/vapor

# Production files
/Public/user_photos/
Public/user_photos/
Public/event_photos/

6 changes: 3 additions & 3 deletions Config/test/vkontakte.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"api_url": "https://api.vk.com/",
"method": "/method/users.get",
"fields": "photo_max,city,verified",
"//": "For tests",
"secret": "c5f95b290abdefb7fb",
"access_token": "40304fc324619460dfb8e2b39d80ead4ecbca2129f3d0e06e20ce155c6506744218bacdae41681ac83553"
"//": "For tests",
"secret": "7a24164e7bdb225b5f",
"access_token": "0dfb80d566999b0aa844cb15ce87909115d431a294bf5d835f2c8d78e5544e5822ed5d5359af812491355"
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,5 @@ extension Date {
let negativeFiveHourseInterval: Double = -18000
return self.addingTimeInterval(negativeFiveHourseInterval)
}

var mysqlString: String {
return DateFormatter.mysql.string(from: self)
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import Foundation

extension FileManager {

func removeAllFiles(atPath: String) throws {

guard fileExists(atPath: atPath) else {
return
}

try contentsOfDirectory(atPath: atPath).forEach { filename in
let filePathToRemove = atPath + filename
try removeItem(atPath: filePathToRemove)
}

}

func removeAllFiles(at dir: URL) throws {

guard fileExists(atPath: dir.path) else {
return
}

try contentsOfDirectory(atPath: dir.path).forEach { filename in
let filePathToRemove = dir.appendingPathComponent(filename)
try removeItem(at: filePathToRemove)
}

}

}
9 changes: 2 additions & 7 deletions Sources/App/Common/Helpers/Constants/Constants.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,15 @@ struct Constants {
static let clientToken = "client-token"
static let domain = "domain"
}

struct Header {
struct Value {
static let applicationJson = "application/json"
}
}

struct Middleware {
static let client = "client-middleware"
static let photoURL = "photoURL-middleware"
}

struct Path {
static let userPhotos = "user_photos"
static let creatorsPhotos = "creator_photos"
static let eventPhotos = "event_photos"
}

struct Status {
Expand Down
34 changes: 21 additions & 13 deletions Sources/App/Common/Helpers/Photo/PhotoController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ struct PhotoController {
self.drop = drop
}

func downloadAndSavePhoto(for event: Event, with url: String?) throws -> String {

guard
let photoURL = url,
photoURL.isNotEmpty,
let eventId = event.id?.string
else {
throw Abort(.badRequest, reason: "Can't get photo from url: '\(url ?? "empty URL")'")
}
return try downloadAndSavePhoto(for: eventId, with: photoURL, folder: Constants.Path.eventPhotos)
}

func downloadAndSavePhoto(for user: User, with url: String?) throws -> String {

guard
Expand All @@ -20,10 +32,10 @@ struct PhotoController {
else {
throw Abort(.badRequest, reason: "Can't get photo from url: '\(url ?? "empty URL")'")
}
return try downloadAndSavePhoto(for: userId, by: photoURL)
return try downloadAndSavePhoto(for: userId, with: photoURL)
}

func downloadAndSavePhoto(for userId: String, by url: String) throws -> String {
func downloadAndSavePhoto(for objectId: String, with url: String, folder: String = Constants.Path.userPhotos) throws -> String {

let request = try drop.client.get(url)
guard let photoBytes = request.body.bytes else {
Expand All @@ -35,12 +47,12 @@ struct PhotoController {
}

let filename = photoURL.lastPathComponent
try savePhoto(for: userId, photoBytes: photoBytes, filename: filename)
try savePhoto(for: objectId, photoBytes: photoBytes, filename: filename, folder: folder)

return filename
}

func savePhoto(for userId: String, photoAsString: String) throws -> String {
func savePhoto(for objectId: String, photoAsString: String, folder: String = Constants.Path.userPhotos) throws -> String {

let filename = UUID().uuidString + ".png"

Expand All @@ -49,25 +61,21 @@ struct PhotoController {
}

let photoBytes = photo.makeBytes()
try savePhoto(for: userId, photoBytes: photoBytes, filename: filename)
try savePhoto(for: objectId, photoBytes: photoBytes, filename: filename, folder: folder)

return filename
}

func savePhoto(for userId: String, photoBytes: Bytes, filename: String) throws {
func savePhoto(for objectId: String, photoBytes: Bytes, filename: String, folder: String = Constants.Path.userPhotos) throws {

let userDir = URL(fileURLWithPath: drop.config.publicDir)
.appendingPathComponent(Constants.Path.userPhotos)
.appendingPathComponent(userId)
.appendingPathComponent(folder)
.appendingPathComponent(objectId)

let fileManager = FileManager.default

if fileManager.fileExists(atPath: userDir.path) {
let filenames = try fileManager.contentsOfDirectory(atPath: userDir.path)
for name in filenames {
let fileURL = userDir.appendingPathComponent(name)
try fileManager.removeItem(at: fileURL)
}
try fileManager.removeAllFiles(at: userDir)
} else {
try fileManager.createDirectory(at: userDir, withIntermediateDirectories: true, attributes: nil)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,32 @@ import Fluent
final class RegistrationController {

let autoapprove = try? AutoapproveController()

let drop: Droplet

init(drop: Droplet) {
self.drop = drop
}

func store(_ request: Request) throws -> ResponseRepresentable {

let user = try request.user()
guard let userId = user.id else {
throw Abort(.internalServerError, reason: "Can't get user.id")
}

guard let regFormId = try request.json?.get(Keys.regFormId) as Identifier! else {
throw Abort(.internalServerError, reason: "Can't get 'fields' and 'reg_form_Id' from request")
guard
let json = request.json,
let regFormIdInt = json[Keys.regFormId]?.int
else {
throw Abort(.internalServerError, reason: "Can't get 'reg_form_Id' from request")
}


let regFormId = Identifier(.int(regFormIdInt))

guard try EventReg.duplicationCheck(regFormId: regFormId, userId: userId) else {
throw Abort(
.internalServerError,
reason: "User with token '\(try user.token())' has alredy registered to this event")
reason: "User with token '\(user.token ?? "")' has alredy registered to this event")
}

guard
Expand All @@ -29,15 +39,17 @@ final class RegistrationController {
else {
throw Abort(.internalServerError, reason: "Can't check autoapprove status")
}

let eventReg = EventReg(
regFormId: regFormId,
userId: userId,
status: grandApprove ? EventReg.RegistrationStatus.approved : EventReg.RegistrationStatus.waiting)
try eventReg.save()

try storeEventRegAnswers(request, eventReg: eventReg)

try drop.mysql().transaction { (connection) in
try eventReg.makeQuery(connection).save()
try storeEventRegAnswers(request, eventReg: eventReg, connection: connection)
}

return eventReg
}

Expand Down Expand Up @@ -68,5 +80,3 @@ extension RegistrationController: ResourceRepresentable {
)
}
}

extension RegistrationController: EmptyInitializable { }
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ extension RegistrationController {

func checkRequired(fieldId: Identifier, answerCount: Int) throws -> Bool {
guard let fieldRequired = try RegField.find(fieldId)?.required else {
throw Abort.serverError
throw Abort(.internalServerError, reason: "Can't get fieldId")
}

if fieldRequired {
Expand All @@ -30,7 +30,7 @@ extension RegistrationController {
}
}

func storeEventRegAnswers(_ request: Request, eventReg: EventReg) throws {
func storeEventRegAnswers(_ request: Request, eventReg: EventReg, connection: Connection? = nil) throws {

guard let eventRegId = eventReg.id else {
throw Abort(.internalServerError, reason: "Can't get eventRegId")
Expand Down Expand Up @@ -62,9 +62,13 @@ extension RegistrationController {
regFieldId: fieldId,
regFieldAnswerId: answerId,
answerValue: answerValue)

try eventRegAnswer.save()
if let conn = connection {
try eventRegAnswer.makeQuery(conn).save()
} else {
try eventRegAnswer.save()
}
}

}
}

Expand Down
65 changes: 65 additions & 0 deletions Sources/App/Controllers/Stage/Samples/ClearDatabase.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import Foundation

//swiftlint:disable superfluous_disable_command
//swiftlint:disable force_try
extension Samples {

func truncateTables() throws {

var tableList: [String]?

var tableForTruncate: [String] {

if tableList != nil {
return tableList!
}

let db = try! drop.assertDatabase()
// swiftlint:disable force_try
guard let nodes = try! db.driver.makeConnection(.read).raw("SHOW TABLES;").array else {
return []
}

let jsons = nodes.map { node -> JSON in
return JSON(node: node)
}

let dbName = drop.config["mysql", "database"]?.string ?? ""
tableList = jsons
.map { json -> String in
json["Tables_in_\(dbName)"]?.string ?? ""
}
.filter { table -> Bool in
table != "social" &&
table != "fluent"
}

return tableList!
}

guard drop.config.environment == .development else {
return
}

let db = try! drop.assertDatabase()

defer {
// swiftlint:disable force_try
try! db.raw("SET FOREIGN_KEY_CHECKS = 1;")
print("Foreign key checks ON\n")
}

try! db.raw("SET FOREIGN_KEY_CHECKS = 0;")
print("\nForeign key checks OFF")

var truncatedTableCount = 0

tableForTruncate.forEach { (table) in
try! db.raw("TRUNCATE \(table)")
truncatedTableCount += 1
}

print("Truncate table(s): \(truncatedTableCount)")

}
}
27 changes: 27 additions & 0 deletions Sources/App/Controllers/Stage/Samples/CreatorSample.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import Vapor

//swiftlint:disable superfluous_disable_command
//swiftlint:disable force_try
extension Samples {

func createCreatorSample() throws {

func createCreator(user: User) throws {

let creator = Creator(
userId: user.id!,
position: user.id!.int!,
info: String.randomValue,
url: String.randomURL,
active: Bool.randomValue
)

try creator.save()
}

try createUserSample(count: 10).forEach { user in
try createCreator(user: user)
}
}

}
Loading

0 comments on commit 3367dbf

Please sign in to comment.