UNPKG

minitel.ts

Version:

A port to typescript and extension of https://github.com/cquest/pynitel

65 lines (64 loc) 3.12 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import * as fs from 'fs'; import * as path from 'path'; import MinitelTSState from './state.js'; export default class MinitelTSRouter { constructor() { this.routes = []; this.current = null; } loadRoutes(routeDir_1) { return __awaiter(this, arguments, void 0, function* (routeDir, initialRoute = 'index') { this.routes = []; const appDir = path.join(path.dirname(process.argv[1]), routeDir); console.log(appDir); const files = fs.readdirSync(appDir); for (const file of files) { if (file.endsWith('.ts') || file.endsWith('.js')) { const p = path.join(appDir, file); const a = yield import(p); this.routes.push({ path: file.replace('.ts', '').replace('.js', ''), name: a.name || file.replace('.ts', '').replace('.js', ''), loop: a.default, state: MinitelTSState({ initial: a.initialState }) }); } // if file is directory, check for directory/index.ts and add it to routes if (fs.statSync(path.join(appDir, file)).isDirectory()) { const indexFileJS = path.join(appDir, file, 'index.js'); const indexFileTS = path.join(appDir, file, 'index.ts'); let indexFile = ''; if (fs.existsSync(indexFileJS)) { indexFile = indexFileJS; } else if (fs.existsSync(indexFileTS)) { indexFile = indexFileTS; } if (fs.existsSync(indexFile)) { const a = yield import(indexFile); this.routes.push({ path: file, name: a.name || file, loop: a.default, state: MinitelTSState({ initial: a.initialState }) }); } } } this.current = this.routes.find(r => r.path === initialRoute) || null; console.log('Routes loaded:', this.routes); }); } goto(route) { this.current = this.routes.find(r => r.path === route || r.name === route) || null; } }