Learn about the Model protocol and the required functions to allow your types to conform to it.
- [Instructor] In Vapor a model is not only a representation of your data, it's also the base protocol for any of your application's models. Especially the ones that you want to persist to a database. A model is only available in Vapor. Its Fluent equivalent is called an entity. When working with a model, you must import Vapor and Fluent. Model objects must conform to the model protocol. When doing so, you'll be informed of some missing items that are required.
First, every model must have a property called id. This is your identifier. It's of optional type node, and it's declared like this. Next, you have to provide a means to create a model from the persisted data. To do so, it should be what's called node initializable. To do this, you need to implement a particular init method, and that signature is init, node, in context and it throws.
What this function tries to do is when pulling data from a database, it's going to try to create your model object, and in doing so will try to build a node from the extracted data from the database. We call try when using node.extract because it'll throw an error if there's a problem. After initializing the model, we'll need to do something to save the model to the database, so we need to make it a node. We'll do that by implementing a method called makeNode, so when a model object is saved, it'll try to convert your corresponding data into a node which will then be saved to the database.
Some databases require you to prepare the database, so preparations will need to be made. This holds true for SQL-driven databases like MySQL and PostgreSQL. First, you'll need a prepare function. This function essentially creates the necessary database tables. Inversely, you'll need a revert function in the event that you need to clear out the database. You have to implement this function for revert.
Something to note is that when reverting a database, you can only do it via the command line interface. Meaning you shouldn't worry that you'll write some code that'll inadvertently delete your data. Also you should rely on Model and Fluent to manage your data. Don't go into your database manually and try to manipulate or remove your data. This is because Fluent keeps track of all of this and trying to manually make changes will throw its tracking methods off, and you could lose tons of data in the process.
- Installing PostgreSQL
- Implementing a database provider and a database driver
- Working with data models
- Implementing functions such as reading, updating, and deleting persisted data
- Working with dynamic Leaf templates
- Handling authentication inside of Vapor
- Creating a login controller
- Securing certain routes within your web service
- Creating a RESTful interface