Step 4: Server-side models
Why you need server-only code
Vulcan models are isomorphic. It means that models work both client-side, for the front-end user interface, and server-side, for the backend business logic.
That makes sense, because models represent real-life objects. Whether you are creating a form or an API endpoint, a blog Author is still an Author, so it's a good practice to share as much code as possible.
However, some code should stay private. For example, the code that process user password belongs to the server. It should not be included in the client bundle and shared to users.
Discover the User and Sample model server code
The User model is a good example of real-life server-only features. The Sample model is also including demonstration of how you could use Vulcan most advanced features to customize your graphql schema.
Open src/models/user.server.ts
and src/models/sampleModel.server.ts
.
You'll see:
- Model specific logic: a bunch of functions related to users
- Server-only fields: fields you don't want to see in the user interface
- Server callbacks: functions that are called on certain events (creation, update, deletion...), like sending an email on success, modifying data before storing them etc.
- Relation field-resolvers: Handle one-to-one and one-to-many relationships elegantly using the relation syntax
- Custom field-resolvers: some data might not be stored outside of your database. For instance, you might want to get information about the user from the Twitter API. To do so, you can use a custom field resolver, with the resolveAs` property.
It is a very advanced model: it handles user signup and authentication. Since those features are related to security, you want them to happen server-side.
Hopefully, your models will be simpler than that most of the time!
Exporting server models
Always remember to export your model in src/models/index.server
to activate this automated generation.
Those models will be automatically added to your GraphQL API and Mongo database. Awesome!
Notice the .server
. In Vulcan, whenever you see a folder named server
, or
a file named *.server.ts
, it means that it contains server-only code.
Customizing the graphQL schema
Have some really custom logic that don't fit in Vulcan Model architecture?
No problem, Vulcan Next has "Just Do It" philosophy: you have full control over your GraphQL schema and Apollo server.
Just check src/pages/api/graphql.ts
to understand the setup.
Models are meant to make your life easier in the early stage of developing your application. But you are completely free to not use them and write your GraphQL API as you wish.
Check š„Vulcan Fire documentation for more info.
Go to step 5
First, please answer this question:
- What does the User model do when creating a new user? (click on the right answer)
- It hashes the provided password before storing it, using the 'create' callback.
- It sends an email to the moderators.