import { ScriptActionTypes } from "./ScriptActionTypes"; import * as fs from "fs"; import * as path from "path"; const Actions = { closeScript(name: string) { return async function(dispatch: Function) { dispatch({ type: ScriptActionTypes.CLOSE_SCRIPT, name, }); }; }, loadScript(file: string) { return async function(dispatch: Function) { const finalPath: string = path.resolve(file); const name: string = path.basename(finalPath); if (fs.existsSync(finalPath)) { try { const content: string = fs.readFileSync(finalPath, "utf-8"); dispatch({ type: ScriptActionTypes.LOAD_SCRIPT, name, content, }); } catch (error) { dispatch({ type: ScriptActionTypes.LOAD_SCRIPT, name, error, }); } } else { dispatch({ type: ScriptActionTypes.LOAD_SCRIPT, name, error: new Error("File not found: " + file), }); } }; }, newScript(name: string, content: string) { return async function(dispatch: Function) { dispatch({ type: ScriptActionTypes.NEW_SCRIPT, name, content, }); }; }, saveScript(file: string, content: string) { const finalPath: string = path.resolve(file); const name: string = path.basename(finalPath); return async function(dispatch: Function) { try { fs.writeFileSync(finalPath, content, "utf-8"); dispatch({ type: ScriptActionTypes.SAVE_SCRIPT, name, content, }); } catch (error) { dispatch({ type: ScriptActionTypes.SAVE_SCRIPT, name, error, }); } }; }, }; export default Actions;