@modern-js/codesmith-api-json
Version:
codesmith json api
49 lines (48 loc) • 1.81 kB
JavaScript
import commentJSON from "comment-json";
import * as declarationUpdate from "declaration-update";
import { editJson } from "./utils";
class JsonAPI {
async get(resource) {
const originJsonValue = await resource.value();
try {
const origin = commentJSON.parse(originJsonValue.content);
return origin;
} catch (e) {
this.generatorCore.logger.debug("❗️ [JSON Get Parse Error]:", e);
throw new Error("resource content is not a legal json");
}
}
async extend(resource, obj, endWithNewLine = false) {
await editJson(this.generatorCore, resource, async () => {
const originJsonValue = await resource.value();
try {
const origin = commentJSON.parse(originJsonValue.content);
const newObj = commentJSON.assign(origin, obj);
const jsonIntent = 2;
return commentJSON.stringify(newObj, void 0, jsonIntent) + (endWithNewLine ? "\n" : "");
} catch (e) {
this.generatorCore.logger.debug("❗️ [JSON Extend Parse Error]:", e);
throw new Error("resource content is not a legal json");
}
});
}
async update(resource, operation, endWithNewLine = false) {
await editJson(this.generatorCore, resource, (text) => {
try {
const jsonContent = commentJSON.parse(text);
declarationUpdate.query(jsonContent, operation.query, operation.update);
const jsonIntent = 2;
return Promise.resolve(commentJSON.stringify(jsonContent, void 0, jsonIntent) + (endWithNewLine ? "\n" : ""));
} catch (e) {
this.generatorCore.logger.debug("❗️ [JSON Update Parse Error]:", e);
throw new Error("resource content is not a legal json");
}
});
}
constructor(generatorCore) {
this.generatorCore = generatorCore;
}
}
export {
JsonAPI
};