Newer
Older
ServerGenerator / src / ExampleOutput / DataAccess.ts
@peter peter on 19 Sep 2020 1 KB Updated code to satisfy eslint.
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Graph, GraphNode } from "./Model";
import * as fs from "fs";
import { parseArrayProperty, parsePrimitiveProperty } from "./util";

type GraphStorage = Graph & { $schema: string; };


export function save(fileName: string, graph: Graph): void {
    const content = JSON.stringify(prepareForWrite(graph));
    fs.writeFileSync(fileName, content);
}

function prepareForWrite(graph: Graph): GraphStorage {
    return { ...graph, $schema: "./graph.schema.json" }
}

function parseGraph(data: any): Graph {
    return {
        nextId: parsePrimitiveProperty<Graph, number>("number", "nextId", 1, data),
        nodes: parseArrayProperty<Graph, GraphNode>("nodes", parseGraphNode, data),
    };
}

function parseGraphNode(data: any): GraphNode
{
    return {
        id: parsePrimitiveProperty<GraphNode, number>("number", "id", 0, data),
        name: parsePrimitiveProperty<GraphNode, string>("string", "name", "", data),
        description: parsePrimitiveProperty<GraphNode, string>("string", "description", "", data),
    };
}

function canReadFile(path: string): boolean {
    try {
        fs.accessSync(path, fs.constants.R_OK);
        return true;
    } catch (error) {
        return false;
    }
}

const emptyGraph: () => Graph = () =>
    ({
        nodes: [],
        nextId: 1,
    });

export function load(fileName: string): Graph {
    if (!canReadFile(fileName)) {
        return emptyGraph();
    }
    const content = fs.readFileSync(fileName).toString();
    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    const data = JSON.parse(content);
    return parseGraph(data);
}