Your First Fullstack App!
Up until now, the app structure has looked like this:
The model is the layer of the application that directly manipulates the data. It provides methods that the controllers can use to execute those changes whenever the frontend makes the appropriate request.
Currently, the model uses an in-memory array to store data. The issue is that the data is not persistent — each time we restart the server, all data created during that "session" is lost.
Now that we have a database and can connect to it using Knex, we can refactor our model to use that database and have our data persist.
Part 1 - Adding a DB for the fellows
create a database called
fellows_tracker_f23Create the table structure
cdintoserver/npm i pg knexnpx knex initto createknexfile.jsin the root of theserver/directorymodify the file to use
pgand thefellow-tracker-f23database with a valid username and passwordcreate a
knex.jsfile in themodel/directorymake sure the import statement for
knexfile.jsis accurate
Refactor
Fellow.js!Import
knexinto theFellowmodelRemove the import of the
getIdfunctionRemove the
Fellow.#allarrayRemove the
constructorentirely and create astatic async createmethod (we'll use the constructor for another purpose)All functions need to be
asyncto useawait knex.raw()Every function needs to return something (use
RETURNING *)Create should return the new fellow
Get ALL should return an array of all fellows
Get One should return a single fellow object (the first object in the
rowsarray)Update should return the updated fellow object
Delete should return the deleted fellow object
Refactor
fellowControllers.jsto use the new model methods and toawaiteverything
Part 2 - Adding posts
Create a posts table that references the fellows table
Create a
Postmodel with methods:create(content, fellowId)
list() (not really used other than for testing)
findById(id) (not really used other than for testing)
findPostsByFellowId(fellowId)
delete(id)
deleteAllPostsForFellow(fellowId)
make the
postControllersdefine endpoints in
index.jstest with postman
add frontend components + fetching on the FellowDetails page
components:
list of posts with delete buttons
form for adding a new post
event handlers / fetching:
useEffect now also fetches fellow posts ->
GET /api/fellows/:fellowId/postslist item delete button on click ->
DELETE /api/posts/:idnew post form on submit ->
POST /api/fellows/:fellowId/posts/:id
when deleting a fellow, we need to delete posts first
Part 3 - Adapters
Create an "adapter" file for fetching fellows and posts
Last updated