使用Vapor 3检查应用程序是否具有最新数据

时间:2018-08-08 11:14:52

标签: postgresql fluent vapor

我正在制作一个使用Vapor 3向测验中添加问题的表格。

我想做的是:

  • 将问题发送到数据库上的“问题”表(完成)
  • 同时/紧随其后使用“数据库版本”更新第二个表

表单与Leaf一起显示

<form action="/save" method="POST" class="form-horizontal" enctype="multipart/form-data" id="upload-form">

并使用Vapor Route触发创建方法

func create(_ req: Request) throws -> Future<Response> {

    return try req.content.decode(ImageUpload.self).flatMap { image in

        if image.image?.filename != "", let img = image.image {

            let uploadDir = try req.sharedContainer.make(DirectoryConfig.self).workDir + "Public/Uploads/"

            let uploadURL = URL(fileURLWithPath: uploadDir + img.filename)
            try image.image?.data.write(to: uploadURL)

        }

        return try req.content.decode(Question.self).flatMap { question in

            if image.image?.filename != "", let img = image.image{
                question.imageName = img.filename
            }

            question.timestamp = Date()

            return question.save(on: req).map { _ in
                return req.redirect(to: "/dbVersion")
            }
        }

    }

还有一个Update方法

func update(_ req: Request) throws -> Future<Response> {



    return try req.parameters.next(Question.self).flatMap { question in
        return try req.content.decode(questionForm.self).flatMap { questionForm in
            question.questionText = questionForm.questionText
            question.answers[0] = questionForm.alt0
            question.answers[1] = questionForm.alt1
            question.answers[2] = questionForm.alt2
            question.answers[3] = questionForm.alt3
            question.theme = questionForm.theme
            question.subject = questionForm.subject
            question.timestamp = Date()

            return question.save(on: req).map { _ in
                return req.redirect(to: "/form")
            }
        }
    }
}

如何在这些方法中运行更新/创建数据库版本?

还是我可以在相同的动作上连续运行这些? :

protectedRouter.post("save", use: questionController.create)
protectedRouter.post("save", use: databaseController.create)

1 个答案:

答案 0 :(得分:1)

感谢您的更新。这不是严格的“蒸气”方法,但我认为这可能更清洁/最简单。虽然,我不太确定您一般需要这样做的原因,或者它有什么好处? :)。我会像创建第二张表一样,但是使用数据库触发器。这样,每次更新行时,您都可以“触发”第二张表中的更新。这是相关的docs,这是一些未经测试的代码。如果这种方法不起作用,请在“蒸汽话语”中找到我,如果您选择这种方法,我可以为您提供帮助。

CREATE TABLE questions (
    question text,
    ...
);

CREATE TABLE db_version (
    id serial,
    db_version_date timestamp
);

CREATE FUNCTION update_version() RETURNS trigger AS $update_version$
    BEGIN

        INSERT INTO db_version SELECT now() ;
        RETURN NULL; -- result is ignored since this is an AFTER trigger
    END;

$update_version$ LANGUAGE plpgsql;

CREATE TRIGGER update_version AFTER INSERT OR UPDATE OR DELETE ON questions
    FOR EACH ROW EXECUTE PROCEDURE update_version();