Skip to content

Commit

Permalink
Replace require with await import where possible (actionhero#1614)
Browse files Browse the repository at this point in the history
* Replace require with await import

* change to for-loop for clarity
  • Loading branch information
evantahler authored Oct 11, 2020
1 parent 8750b06 commit 4aca28d
Show file tree
Hide file tree
Showing 21 changed files with 95 additions and 66 deletions.
4 changes: 3 additions & 1 deletion __tests__/core/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import * as isrunning from "is-running";

const testDir = path.join(process.cwd(), "tmp", "actionheroTestProject");
const binary = "./node_modules/.bin/actionhero";
const pacakgeJSON = require(path.join(__dirname, "/../../package.json"));
const pacakgeJSON = JSON.parse(
fs.readFileSync(path.join(__dirname, "/../../package.json")).toString()
);

console.log(`testDir: ${testDir}`);

Expand Down
3 changes: 2 additions & 1 deletion __tests__/core/staticFile/staticFile.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import * as request from "request-promise-native";
import * as child_process from "child_process";
import { Process, config, utils, specHelper } from "../../../src/index";

const actionhero = new Process();
let url;

async function exec(command) {
return new Promise((resolve, reject) => {
require("child_process").exec(command, (error, stdout, stderr) => {
child_process.exec(command, (error, stdout, stderr) => {
if (error) {
return reject(error);
}
Expand Down
5 changes: 4 additions & 1 deletion __tests__/integration/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
*/

import * as path from "path";
import * as fs from "fs";
import { api, Process, config } from "./../../src/index";
const packageJSON = require(path.join(__dirname, "..", "..", "package.json"));
const packageJSON = JSON.parse(
fs.readFileSync(path.join(__dirname, "..", "..", "package.json")).toString()
);
const host = process.env.SELENIUM_TEST_HOST || "localhost";

const actionhero = new Process();
Expand Down
12 changes: 9 additions & 3 deletions src/actions/status.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { api, id, task, Action, actionheroVersion } from "./../index";
import * as path from "path";
const packageJSON = require(path.normalize(
path.join(__dirname, "..", "..", "package.json")
));
import * as fs from "fs";

const packageJSON = JSON.parse(
fs
.readFileSync(
path.normalize(path.join(__dirname, "..", "..", "package.json"))
)
.toString()
);

// These values are probably good starting points, but you should expect to tweak them for your application
const maxEventLoopDelay = process.env.eventLoopDelay || 10;
Expand Down
27 changes: 13 additions & 14 deletions src/bin/actionhero.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,9 @@ const projectRoot = determineProjectRoot();
const handleUnbuiltProject = async (commands: Array<string>) => {
try {
// when generating the project from scratch, we cannot rely on the normal initializers
const ExportedRunnerClasses = require(path.join(
__dirname,
"methods",
commands.join(path.sep)
));
const ExportedRunnerClasses = await import(
path.join(__dirname, "methods", commands.join(path.sep))
);

if (Object.keys(ExportedRunnerClasses).length > 1) {
throw new Error("actionhero CLI files should only export one method");
Expand All @@ -101,7 +99,7 @@ const projectRoot = determineProjectRoot();
console.log(`ACTIONHERO COMMAND >> ${commands.join(" ")}`);
console.log("⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻⁻");

const { config, Process } = require(path.join(__dirname, "..", "index"));
const { config, Process } = await import("../index");
const actionHeroProcess = new Process();
await actionHeroProcess.initialize();

Expand All @@ -111,26 +109,27 @@ const projectRoot = determineProjectRoot();
let p: string;
p = path.join(__dirname, "methods", commands.join(path.sep) + ".js");
if (fs.existsSync(p) && config.general.cliIncludeInternal !== false) {
ExportedClasses = require(p);
ExportedClasses = await import(p);
}

p = path.join(__dirname, "methods", commands.join(path.sep) + ".ts");
if (fs.existsSync(p) && config.general.cliIncludeInternal !== false) {
ExportedClasses = require(p);
ExportedClasses = await import(p);
}

if (!ExportedClasses) {
config.general.paths.cli.forEach((cliPath: string) => {
for (const i in config.general.paths.cli) {
const cliPath = config.general.paths.cli[i];
p = path.join(cliPath, commands.join(path.sep) + ".js");
if (fs.existsSync(p)) {
ExportedClasses = require(p);
ExportedClasses = await import(p);
}

p = path.join(cliPath, commands.join(path.sep) + ".ts");
if (fs.existsSync(p)) {
ExportedClasses = require(p);
ExportedClasses = await import(p);
}
});
}
}

if (!ExportedClasses) {
Expand All @@ -139,7 +138,7 @@ const projectRoot = determineProjectRoot();
const pluginPath = config.plugins[pluginName].path;
p = path.join(pluginPath, "bin", commands.join(path.sep) + ".js");
if (fs.existsSync(p)) {
ExportedClasses = require(p);
ExportedClasses = await import(p);
}

p = path.join(
Expand All @@ -149,7 +148,7 @@ const projectRoot = determineProjectRoot();
commands.join(path.sep) + ".js"
);
if (fs.existsSync(p)) {
ExportedClasses = require(p);
ExportedClasses = await import(p);
}
}
}
Expand Down
12 changes: 5 additions & 7 deletions src/bin/methods/generate/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@ import * as fs from "fs";
import * as path from "path";
import { CLI, utils } from "./../../../index";

const PackageJSON = require(path.join(
__dirname,
"..",
"..",
"..",
"package.json"
));
const PackageJSON = JSON.parse(
fs
.readFileSync(path.join(__dirname, "..", "..", "..", "package.json"))
.toString()
);

export class GeneratePlugin extends CLI {
constructor() {
Expand Down
7 changes: 4 additions & 3 deletions src/bin/methods/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,10 @@ export class Help extends CLI {

files = utils.arrayUnique(files);

files.forEach((f) => {
for (const i in files) {
const f = files[i];
try {
const ExportedClasses = require(f);
const ExportedClasses = await import(f);
const req = new ExportedClasses[Object.keys(ExportedClasses)[0]]();
if (
req.name &&
Expand All @@ -63,7 +64,7 @@ export class Help extends CLI {
methods[req.name] = req;
}
} catch (e) {}
});
}

const methodNames = Object.keys(methods).sort();

Expand Down
6 changes: 5 additions & 1 deletion src/bin/methods/version.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import * as path from "path";
import * as fs from "fs";

// import { CLI } from "./../../index";
// we need to load each component directly so we don't accidentally source `config... which doesn't exist`
import { CLI } from "./../../classes/cli";

const packageJSON = require(path.join(__dirname, "/../../../package.json"));
const packageJSON = JSON.parse(
fs.readFileSync(path.join(__dirname, "/../../../package.json")).toString()
);

export class Version extends CLI {
constructor() {
Expand Down
3 changes: 2 additions & 1 deletion src/classes/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { api } from "../index";
/**
* Create a new Actionhero Action. The required properties of an action. These can be defined statically (this.name) or as methods which return a value.
*```js
* const { Action } = require('actionhero')
* import { Action } from "actionhero";
*
* module.exports = class RandomNumber extends Action {
* constructor () {
* super()
Expand Down
7 changes: 4 additions & 3 deletions src/classes/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,14 @@ export class Process {
initializerFiles = utils.arrayUnique(initializerFiles);
initializerFiles = utils.ensureNoTsHeaderFiles(initializerFiles);

initializerFiles.forEach((f) => {
for (const i in initializerFiles) {
const f = initializerFiles[i];
const file = path.normalize(f);
if (require.cache[require.resolve(file)]) {
delete require.cache[require.resolve(file)];
}

let exportedClasses = require(file);
let exportedClasses = await import(file);

// allow for old-js style single default exports
if (typeof exportedClasses === "function") {
Expand Down Expand Up @@ -226,7 +227,7 @@ export class Process {
stopInitializerRankings[initializer.stopPriority].push(stopFunction);
}
}
});
}

// flatten all the ordered initializer methods
this.loadInitializers = this.flattenOrderedInitializer(
Expand Down
13 changes: 6 additions & 7 deletions src/classes/process/actionheroVersion.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import * as path from "path";
import * as fs from "fs";

const packageJson = require(path.join(
__dirname,
"..",
"..",
"..",
"package.json"
));
const packageJson = JSON.parse(
fs
.readFileSync(path.join(__dirname, "..", "..", "..", "package.json"))
.toString()
);

export const actionheroVersion = packageJson.version;
3 changes: 2 additions & 1 deletion src/classes/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { Inputs } from "./inputs";
/**
* Create a new Actionhero Task. The required properties of an task. These can be defined statically (this.name) or as methods which return a value.
* ```js
* const { Task, api, log } = require('actionhero')
* import { Task, api, log } from "actionhero"
*
* module.exports = class SayHello extends Task {
* constructor () {
* super()
Expand Down
9 changes: 7 additions & 2 deletions src/config/api.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
const path = require("path");
import * as path from "path";
import * as fs from "fs";

export const DEFAULT = {
general: (config) => {
const packageJSON = require("./../../package.json");
const packageJSON = JSON.parse(
fs
.readFileSync(path.join(__dirname, "..", "..", "package.json"))
.toString()
);

return {
apiVersion: packageJSON.version,
Expand Down
9 changes: 6 additions & 3 deletions src/config/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ let db = process.env.REDIS_DB || process.env.JEST_WORKER_ID || "0";
let password = process.env.REDIS_PASSWORD || null;
const maxBackoff = 1000;

// this cannot be imported as the ioredis types are not exported for --declaration
const Redis = require("ioredis");

if (process.env.REDIS_URL) {
const parsed = new URL(process.env.REDIS_URL);
if (parsed.password) {
Expand Down Expand Up @@ -51,17 +54,17 @@ export const DEFAULT = {

_toExpand: false,
client: {
konstructor: require("ioredis"),
konstructor: Redis,
args: [commonArgs],
buildNew: true,
},
subscriber: {
konstructor: require("ioredis"),
konstructor: Redis,
args: [commonArgs],
buildNew: true,
},
tasks: {
konstructor: require("ioredis"),
konstructor: Redis,
args: [commonArgs],
buildNew: true,
},
Expand Down
2 changes: 1 addition & 1 deletion src/config/servers/web.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const os = require("os");
import * as os from "os";

export const DEFAULT = {
servers: {
Expand Down
2 changes: 1 addition & 1 deletion src/initializers/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export class Actions extends Initializer {
let action;

try {
let collection = require(fullFilePath);
let collection = await import(fullFilePath);
if (typeof collection === "function") {
collection = [collection];
}
Expand Down
2 changes: 1 addition & 1 deletion src/initializers/servers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export class Servers extends Initializer {

for (const j in files) {
const filename = files[j];
const ExportedClasses = require(filename);
const ExportedClasses = await import(filename);

const exportLen = Object.keys(ExportedClasses).length;
// we have named exports
Expand Down
27 changes: 14 additions & 13 deletions src/initializers/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ export class Tasks extends Initializer {
globalMiddleware: [],
};

api.tasks.loadFile = (fullFilePath: string, reload = false) => {
api.tasks.loadFile = async (fullFilePath: string, reload = false) => {
let task;
let collection = require(fullFilePath);
let collection = await import(fullFilePath);
for (const i in collection) {
const TaskClass = collection[i];
task = new TaskClass();
Expand Down Expand Up @@ -134,16 +134,17 @@ export class Tasks extends Initializer {
};
};

api.tasks.loadTasks = (reload) => {
config.general.paths.task.forEach((p) => {
utils
.ensureNoTsHeaderFiles(
glob.sync(path.join(p, "**", "**/*(*.js|*.ts)"))
)
.forEach((f) => {
api.tasks.loadFile(f, reload);
});
});
api.tasks.loadTasks = async (reload) => {
for (const i in config.general.paths.task) {
const p = config.general.paths.task[i];
await Promise.all(
utils
.ensureNoTsHeaderFiles(
glob.sync(path.join(p, "**", "**/*(*.js|*.ts)"))
)
.map((f) => api.tasks.loadFile(f, reload))
);
}

for (const pluginName in config.plugins) {
if (config.plugins[pluginName].tasks !== false) {
Expand All @@ -163,7 +164,7 @@ export class Tasks extends Initializer {
}
};

api.tasks.loadTasks(false);
await api.tasks.loadTasks(false);

// we want to start the queue now, so that it's available for other initializers and CLI commands
await api.resque.startQueue();
Expand Down
4 changes: 4 additions & 0 deletions src/modules/specHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ export namespace specHelper {
taskName: string,
params: object | Array<any>
): Promise<{ [key: string]: any }> {
if (!api.tasks.tasks[taskName]) {
throw new Error(`task ${taskName} not found`);
}

return api.tasks.tasks[taskName].run(params);
}

Expand Down
2 changes: 1 addition & 1 deletion src/modules/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ export namespace task {
api.tasks.middleware
);
}
api.tasks.loadTasks(true);
await api.tasks.loadTasks(true);
}

async function validateInput(taskName: string, inputs: TaskInputs) {
Expand Down
2 changes: 1 addition & 1 deletion templates/boot.js.template
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* This file will load, be `require()`d, first in the actionhero binary.
/* This file will load, be required, first in the actionhero binary.
Anything that needed loaded or run BEFORE actionhero starts can be done here.

This file returns a single method that is run immediately after loading.
Expand Down

0 comments on commit 4aca28d

Please sign in to comment.