Part 3 - Prepare demo data
This is part 3 in this series
Now that we have our GraphQL endpoint working. It’s time to get some data for newsfeed demo app.
Create fake database
If you’re looking at the source of Newsfeed Demo app here, you can see that they hardcode the data in a nodes
variable. Let’s do just that, but in Python.
Outline:
- Copy and paste fake data from relay-examples
- Update urls for the images hardcoded in fake data
- Create a
db
module to use as the “database” for our demo app.
Here’s the json file that we have after step 1 & 2: https://github.com/tuan/newsfeed-demo-app/commit/3b5c3ef2dc31108446caef8f44f6175d70e00aa4
Notice that, compared to the urls in relay-examples, our urls start with /static
. This is to match with current STATIC_URL
we have in settings.py
.
Before we move on, let’s test to make sure the fake data is correctly loaded. Let’s start Python interpreter in the root of the project
import json
from pathlib import Path
import pprint
fakedata = Path('db') / 'fake_data.json'
with open(fakedata, 'r') as data:
nodes = json.load(data)
pprint.pprint(nodes)
Commit: https://github.com/tuan/newsfeed-demo-app/commit/0123f828e056c0cf86ef75a003ed543d30b7ebda
This is a short one, but important step before we can start learning Relay next!
Serve images from Django
The Newsfeed demo app has images used as profile pictures and post attachments. Where do we store those images ? In Django project or Vite ?
In production apps, such assets are created and uploaded by users. They are stored in our database or a blob storage. When clients request these assets, we either serve them directly from the storage or, better, via CDN. What this means is those static assets will not be bundled, and therefore, served by our Vite devserver during development. For this demo, we should serve them from Django.
Outline:
- Copy and paste images from relay-examples
- Set up Django to serve static assets that are not bundled by Vite
Let’s create a static
folder at the root of our project and copy all images to a assets
subfolder.
We’re now in a interesting situation. During development, we have 2 different sets of static assets: one is served by Vite and one is served by Django. Let’s make explicit in our setup.
Outline:
- Update baseURL in vite.config.ts to
/static/vite
- Update settings.py to tell Django that it should look for static assets from 2 different locations: Vite’s dist folder and Django’s static folder.
Commit: https://github.com/tuan/newsfeed-demo-app/commit/7e2c50a497c8d8b3b2adecbed643888b60078427
After making the changes, let’s test the following:
-
Homepage still loads correctly by going to http://localhost:8000
-
Images are being served directly by Django by fetching a random image in static/assets folder: http://localhost:8000/static/assets/yak.png