Skip to content

Server Side Rendering

JP DeVries edited this page Mar 18, 2017 · 4 revisions

To demonstrate server side rendering via Node this example assumes you are using Express, Formidable, and some promises.

import React from 'react';
import ReactDOM from 'react-dom';

import EurekaMediaBrowser from 'EurekaMediaBrowser';

app.get('/eureka', (req, res) => {

});

app.post('/eureka', (req, res) => {
  const form = new formidable.IncomingForm();
  form.multiples = true;

  form.parse(req, function(err, fields, files) {
    const uploadFiles = files.eureka__uploadFiles;

    const [cs, cd] = utility.parseMediaSourceOutOfCombinedPath(fields[`eureka__media-browser_${fields.eureka__mediaSourceId}__browsing`], '||');
    const uploadDir = path.join(__dirname, path.join('/sources/filesystem/', fields['eureka__upload-dir']));

    function moveFile(file) {
      fs.renameSync(file.path, path.join(uploadDir, file.name))
    }

    try {
      uploadFiles.map(moveFile)
    } catch (e) { // its a single file not an Array
      if(uploadFiles.name) moveFile(uploadFiles)
    }

    if(fields.eureka__chosen_item) { // if they chose an item
      getMediaSources().then((mediaSources) => {
        const name = mediaSources.filter((mediaSource) => (
          mediaSource.id == cs
        ))[0].name || undefined;

        // this is where you redirect or do whatever you'd like once they have chosen an item
        res.end(`<!DOCTYPE html>
        <html lang="en">
          <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width,initial-scale=1">
            <title data-site-name="Eureka Media Browser">Eureka!</title>
          </head>
          <body>
            <h1>Eureka!</h1>
            <p>You chose ${path.join(fields['eureka__upload-dir'], fields.eureka__chosen_item)} of the ${name} (${cs}) media&nbsp;source.</p>
            <img src="/sources/filesystem/${path.join(fields['eureka__upload-dir'], fields.eureka__chosen_item)}" alt="/sources/filesystem/${path.join(fields['eureka__upload-dir'], fields.eureka__chosen_item)}" />
          </body>
        </html>`);
      });
    } else { // if they didn't chose something, they browsed or uploaded so time to serve them the media browser again
      serveEureka(cd).then((eurekaMarkup) => {
        res.end(`<!DOCTYPE html>
        <html lang="en">
          <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width,initial-scale=1">
            <title data-site-name="Eureka Media Browser">Eureka Media Browser</title>
            <link rel="stylesheet" href="assets/css/components/eureka/eureka.2.0.0.min.css">
          </head>
          <body>
            <div id="root">${eurekaMarkup}</div>
          </body>
        </html>`);
      });
    }
  });

});

function serveEureka(dir = "/") {
  return new Promise((resolve, reject) => {
    getMediaSources().then((mediaSources) => (
      store.dispatch(actions.fetchMediaSourcesSuccess((
        mediaSources
      )))
    )).then(() => {
      return new Promise((resolve, reject) => { // get the media source tree listing
        const path = `${__dirname}/sources/filesystem/`;
        //const data = [{"name":"assets","cd":"assets","children":[{"name":"img","cd":"assets/img","children":[{"name":"hawaii","cd":"assets/img/hawaii","children":[]},{"name":"redwoods","cd":"assets/img/redwoods","children":[]}]},{"name":"screenshots","cd":"assets/screenshots","children":[]},{"name":"uploads","cd":"assets/uploads","children":[]}]},{"name":"camera","cd":"camera","children":[]},{"name":"foo","cd":"foo","children":[]}];
        recursivelyGetSourceDirectories(path).then((results) => (
          resolve(results)
        )).catch((err) => (
          res.json([])
        ));
      })
    }).then((results) => (
      store.dispatch(actions.updateSourceTreeSuccess(
        results
      ))
    )).then(() => { // get the current directory listing
      return new Promise((resolve, reject) => {
        getDirectoryListing(`${__dirname}/sources/filesystem/`, dir || 'assets/img/hawaii', true, true, `${__dirname}/sources/filesystem/`).then((results) => (
          resolve(results)
        )).catch((err) => (
          res.json([])
        ));

      })
    }).then((results) => (
      store.dispatch(actions.fetchDirectoryContentsSuccess(
        results
      ))
    )).then(() => (
      store.dispatch(actions.updateContent({ // updates the "current directory" of the view right away
        cd: dir
      }))
    )).then(() => {
      const eurekaMarkup = ReactDOM.renderToStaticMarkup(
        <EurekaMediaBrowser
        uid="0"
        currentDirectory={dir} />
      );
      resolve(eurekaMarkup);
    });
  });
}

function getMediaSources() {
  return new Promise((resolve, reject) => {
    /* this is where you get your media source information (data base query, whatever) and then return it with resolve() */
  })
}

function getDirectoryListing() {
  return new Promise((resolve, reject) => {
    /* this is where you get your directory listing information (data base query, whatever) and then return it with resolve() */
  })
}

Clone this wiki locally