Store data for organizations
Learn how to store data for organizations in your supastarter application.
When working with organizations, you most likely want to store data for each organization that can be accessed by the organization members.
We are re-using the post example from the API documentation and extend it to store the organiaztion with it. Let's assume you want to enable all members of an organization to edit the posts of the organization instead of just the author.
You probably still want the individual author to be defined on the post, so you can still see who created the post.
Adjust the database schema
To do this, you can add the organizationId
field in the post schema.
Add organizationId to the post creation endpoint
To create a post now, you need to pass the organizationId
to the endpoint.
This resolver is protected by the authMiddleware
which means only authenticated users can access it.
Beyond that, we are checking if the user is a member of the organization with the verifyOrganizationMembership
helper function.
If the user is not a member, the function will throw an error and the request will not be processed further.
Create a post from the UI
To create a post from the UI, create a useCreateOrganizationPostMutation
hook.
When using this mutation, you need to pass the organizationId
that you can get from the useActiveOrganization
hook.
Make sure to only call this mutation when there is an active organization.
Add organizationId to the post query endpoint
Now you probably want to query the posts of an organization to list them in the UI.
To do this, you can add the organizationId
to the endpoint which lists all posts.
This endpoint will fetch all posts of the organization and return them as a JSON response.
Query posts by organization in the UI
Lastly, to query the posts by organization in the UI, you can create a query that takes an organizationId
:
Now inside your component, you can use the useOrganizationPostsQuery
hook to fetch the posts of an organization.