From 11e3c32eb9f971e16de3682e90ec4d417f38a151 Mon Sep 17 00:00:00 2001 From: cha0s Date: Sat, 23 Jan 2021 16:11:31 -0600 Subject: [PATCH] feat: default state --- packages/core/src/server/index.js | 46 +++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/packages/core/src/server/index.js b/packages/core/src/server/index.js index 0bc0c36..56f4b5d 100644 --- a/packages/core/src/server/index.js +++ b/packages/core/src/server/index.js @@ -1,5 +1,14 @@ +import fs from 'fs'; +import {join} from 'path'; +import {promisify} from 'util'; + import {decorateWithLatus, gatherWithLatus} from '@latus/core'; +import {treeToPaths} from '../tree-utils'; + +const readFile = promisify(fs.readFile).bind(fs); +const stat = promisify(fs.stat).bind(fs); + export default { hooks: { '@latus/db/server/models': gatherWithLatus( @@ -8,5 +17,42 @@ export default { '@latus/db/server/models.decorate': decorateWithLatus( require.context('../models/decorators', false, /\.js$/), ), + '@latus/redux/defaultState': async (req) => { + const projects = req + ? await req.user.projects() + : {}; + const resources = await Object.entries(projects) + .reduce(async (r, [uuid, structure]) => ({ + ...(await r), + ...( + await (await Promise.all(treeToPaths(structure) + .map(async (path) => { + try { + return [ + path, + (await stat(join(process.cwd(), 'projects', uuid, path))).isFile(), + ]; + } + catch (error) { + return [path, false]; + } + }))) + .filter(([, stat]) => stat) + .map(([path]) => path) + .reduce(async (r, path) => ({ + ...(await r), + [join(uuid, path)]: ( + await readFile(join(process.cwd(), 'projects', uuid, path)) + ).toString('base64'), + }), {}) + ), + }), {}); + return { + projects: { + projects, + resources, + }, + }; + }, }, };