ExampleStore.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const scandir = require('./scandir');
  2. var Promise = require('bluebird');
  3. var _ = require('lodash');
  4. function ExampleStore(path) {
  5. this.rootPath = path;
  6. this.repos = [];
  7. }
  8. ExampleStore.prototype.init = function() {
  9. const loadRepository = this.loadRepository.bind(this);
  10. return scandir(this.rootPath, ['.gitkeep'])
  11. .then(repositories => Promise.map(
  12. repositories, loadRepository
  13. ));
  14. };
  15. ExampleStore.prototype.loadRepository = function(repoPath) {
  16. const loadExample = this.loadExample.bind(this);
  17. const fullPath = this.rootPath + '/' + repoPath;
  18. const repoConfig = require(fullPath + '/repo-config.json');
  19. const repoDescriptor = {
  20. title: repoConfig.title,
  21. path: repoPath,
  22. fullPath,
  23. examples: []
  24. };
  25. this.repos.push(repoDescriptor);
  26. return scandir(fullPath, ['.gitkeep', 'repo-config.json'])
  27. .then(examples => Promise.map(
  28. examples, example => loadExample(repoDescriptor, example)
  29. ))
  30. .then(() => console.log(this.repos[0]))
  31. };
  32. ExampleStore.prototype.loadExample = function(repo, slug) {
  33. const exampleConfig = require(repo.fullPath + '/' + slug + '/config.json');
  34. repo.examples.push(Object.assign({ slug }, exampleConfig));
  35. return exampleConfig;
  36. };
  37. ExampleStore.prototype.getList = function(path) {
  38. return _.find(this.repos, { path });
  39. }
  40. ExampleStore.prototype.getRepoMenu = function(path) {
  41. return this.repos.map(
  42. ({ title, path }) => ({ title, slug: path })
  43. )
  44. };
  45. ExampleStore.prototype.getExampleMenu = function(path) {
  46. const repo = _.find(this.repos, { path });
  47. return repo.examples.map(
  48. ({ title, slug }) => ({ title, slug: repo.path + '/' + slug })
  49. );
  50. };
  51. ExampleStore.prototype.getMenu = function(path) {
  52. const self = this;
  53. return '<ul>' + self.repos.reduce((menu, repo) => {
  54. return menu + '<li>'+ repo.title + '<ul>' + repo.examples.reduce((submenu, example) =>
  55. (submenu + '<li><a href="#' + repo.path + '/' + example.slug + '">' + example.title + '</a></li>'),
  56. '') + '</ul></li>';
  57. }, '') + '</ul>';
  58. }
  59. ExampleStore.prototype.getRepo = function(path) {
  60. return _.find(this.repos, { path });
  61. }
  62. module.exports = ExampleStore;