Gator is a multi-user CLI application. There's no server (other than the database), so it's only intended for local use, but just like games in the 90's and early 2000's, that doesn't mean we can't have multiplayer functionality on a single device!
We'll use a single JSON file to keep track of two things:
The JSON file should have this structure (when prettified):
{
"db_url": "connection_string_goes_here",
"current_user_name": "username_goes_here"
}
Note: There's no user-based authentication for this app. If someone has the database credentials, they can act as any user. We'll cover auth in other courses. We want to focus on SQL, CLIs and long-running services for this project.
{
"db_url": "postgres://example"
}
Don't worry about adding current_user_name, that will be set by the application.
This file should have the following functionality exported:
I used os.homedir to get the location of HOME.
I also wrote a few non-exported helper functions.
getConfigFilePath(): stringwriteConfig(cfg: Config): voidvalidateConfig(rawConfig: any): Config - used by readConfig to validate the result of JSON.parse.JSON.parse is typed as any because it can return any type of object. We need to validate the object to ensure it has the correct structure.
I imported the fs, os, and path modules:
import fs from "fs";
import os from "os";
import path from "path";
fs is the file system module, which allows you to read and write files.os provides operating system-related utility methods.path provides utilities for working with file and directory paths.But you can implement the internals however you like.
If you want additional help, see the Tips section below.
Run and submit the CLI tests from the root of your project.
To read and write to JSON, I used:
fs.readFileSync(path[,options]) and set the encoding to 'utf-8'.fs.writeFileSync(file, data[, options]) after using JSON.stringifyTo get the path to read and write to, I used: