hwakabh / hwakabh.github.io

Personal Web Page
https://hwakabh.github.io/
0 stars 0 forks source link

Enable to read JSON for fetching static contents as API responses #63

Closed hwakabh closed 9 months ago

hwakabh commented 9 months ago

AsIs

Currently the responses of backend API are hardcoded in code basis. Since some endpoints of backend API will return JSON responses from file as application requirements, firstly we have to enable feature to fetch JSON data from file, which exists same repository as backend project.

ToBe

It seems that we can use module fs for enable this, research how to play with it, and implement to backend API.

(Optional) Acceptance

Confirm we can see data in JSON file with calling API locally.

(Optional) Additional Contexts

Relates: #62

hwakabh commented 9 months ago

Sanity testings with JSON files

Create test JSON data file with creating directory in application root, app/data/project.json

{
  "title": "Project Title here",
  "descriptions": "Project descriptions here",
  "skills": [ "Linux", "Kubernetes" ]
}

Newly create app/routes/project.js for application routings. As minimal sample, we can fetch data from JSON file with require() method of Node.js. Note that we have to also update app.js with importing router from routes/projects.json and adding to root.

// (...)
const projects = require(__dirname + "/../data/project.json");

res.header('Content-Type', 'application/json; charset=utf-8');
res.json(projects);

Then starting application with npm start, yarn run start, or node bin/www, confirmed with curl:

# Confirmed we can GET json data
24-01-24 23:36:21 ~  % curl -s -X GET localhost:3000/projects |jq .
{
  "title": "Project Title here",
  "descriptions": "Project descriptions here",
  "skills": [
    "Linux",
    "Kubernetes"
  ]
}

# And header seems to be fine
24-01-24 23:43:36 ~  % curl -D - -o /dev/null -s -X GET localhost:3000/projects      
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 105
ETag: W/"69-762BpDSi+TMNSrlHbKIMC+K1c7I"
Date: Wed, 24 Jan 2024 14:43:49 GMT
Connection: keep-alive
Keep-Alive: timeout=5
hwakabh commented 9 months ago

Regarding JSON, there is a caveat to manage our data for apps, since as requirements we have to store Project Information into the files, which might contain long string lines. Whereas JSON could not allow line wrapping with long string, so it is hard that we have to maintain the JSON files.

Considering alternatives, there are following options, but we will adopt json5 for its readability and friendliness with JavaScript/TypeScript.

Also we could use some formats for binary-serialization specific, but seems they are too much for us, so declined.