@gluestack-v2/glue-plugin-service-gateway
Version:
Gluestack V2 service Gateway Plugin
404 lines (401 loc) • 22.1 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
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());
});
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "@gluestack-v2/framework-cli/build/helpers/print", "fs", "../package.json", "./PluginInstance", "@gluestack-v2/framework-cli/build/plugin/BaseGluestackPlugin", "@gluestack-v2/framework-cli/build/helpers/file/read-file", "path", "@gluestack/helpers", "path", "./helpers/write-service", "./helpers/write-queues-service", "./helpers/write-cron-service", "./helpers/write-db-client-service", "./helpers/template", "./helpers/writeMinioStorageService"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GlueStackPlugin = void 0;
const print_1 = require("@gluestack-v2/framework-cli/build/helpers/print");
const fs_1 = __importStar(require("fs"));
// @ts-ignore
const package_json_1 = __importDefault(require("../package.json"));
const PluginInstance_1 = require("./PluginInstance");
const BaseGluestackPlugin_1 = __importDefault(require("@gluestack-v2/framework-cli/build/plugin/BaseGluestackPlugin"));
const read_file_1 = __importDefault(require("@gluestack-v2/framework-cli/build/helpers/file/read-file"));
const path_1 = require("path");
const helpers_1 = require("@gluestack/helpers");
const path_2 = __importDefault(require("path"));
const write_service_1 = __importDefault(require("./helpers/write-service"));
const write_queues_service_1 = __importDefault(require("./helpers/write-queues-service"));
const write_cron_service_1 = __importDefault(require("./helpers/write-cron-service"));
const write_db_client_service_1 = __importDefault(require("./helpers/write-db-client-service"));
const template_1 = require("./helpers/template");
const writeMinioStorageService_1 = require("./helpers/writeMinioStorageService");
// Do not edit the name of this class
class GlueStackPlugin extends BaseGluestackPlugin_1.default {
constructor(app, gluePluginStore) {
super(app, gluePluginStore);
this.type = 'devonly';
this.gluePluginStore = gluePluginStore;
}
init() {
this.app.addEventListener('booting.web', (...args) => {
// eslint-disable-next-line no-console
console.log({ message: 'booting web event listener', args });
// eslint-disable-next-line no-console
console.log(this.gluePluginStore.get('message'));
this.gluePluginStore.set('message', 'Hello from function plugin');
// eslint-disable-next-line no-console
console.log(this.gluePluginStore.get('message'));
});
}
destroy() {
//
}
getName() {
return package_json_1.default.name;
}
getVersion() {
return package_json_1.default.version;
}
getType() {
return this.type;
}
// getInstallationPath(target: string): string {
// return `./.glue/__generated__/bolt/services/${target}/src/${target}`;
// }
runPostInstall(instanceName) {
return __awaiter(this, void 0, void 0, function* () {
const instance = yield this.app.createPluginInstance(this, instanceName, this.getTemplateFolderPath()
// target
);
if (!instance) {
return;
}
});
}
createInstance(key, gluePluginStore, installationPath) {
const instance = new PluginInstance_1.PluginInstance(this.app, this, key, gluePluginStore, installationPath !== null && installationPath !== void 0 ? installationPath : '');
this.instances.push(instance);
return instance;
}
getInstances() {
return this.instances;
}
generateService(instancePath, instanceName
// ignoredPaths: string[]
) {
var _a, e_1, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
const instances = this.getInstances();
if (this.instances.length === 0) {
return;
}
try {
for (var _d = true, instances_1 = __asyncValues(instances), instances_1_1; instances_1_1 = yield instances_1.next(), _a = instances_1_1.done, !_a;) {
_c = instances_1_1.value;
_d = false;
try {
const instance = _c;
const functionsPath = path_2.default.resolve(process.cwd(), instancePath);
if (!(yield (0, helpers_1.fileExists)(functionsPath))) {
console.error('> No functions plugin found, create instance first');
}
else {
(0, write_service_1.default)(instance._destinationPath, instancePath, instanceName
// ignoredPaths
);
}
}
finally {
_d = true;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_d && !_a && (_b = instances_1.return)) yield _b.call(instances_1);
}
finally { if (e_1) throw e_1.error; }
}
});
}
generateQueuesService(queueInstanceName) {
var _a, e_2, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
if (this.instances.length === 0) {
return;
}
const instances = this.getInstances();
try {
for (var _d = true, instances_2 = __asyncValues(instances), instances_2_1; instances_2_1 = yield instances_2.next(), _a = instances_2_1.done, !_a;) {
_c = instances_2_1.value;
_d = false;
try {
const instance = _c;
const targetPkgJson = (0, path_1.join)(instance._destinationPath, 'package.json');
if (yield (0, helpers_1.fileExists)(targetPkgJson)) {
const data = yield require(targetPkgJson);
if (!data.devDependencies) {
data.devDependencies = {};
}
// hard-coded the version here
data.devDependencies['moleculer-bee-queue'] = '^0.1.10';
const stringData = JSON.stringify(data, null, 2);
fs_1.default.writeFileSync(targetPkgJson, stringData);
(0, print_1.success)("We have added moleculer-bee-queue to your service-gateway package.json\n Please run 'npm install' to install the package\n and restart your service-gateway instance \n");
}
else {
(0, print_1.warning)('We could not find the package.json for service-gateway instance\n Please add moleculer-bee-queue to your service-gateway package.json\n and restart your service-gateway instance \n');
}
(0, write_queues_service_1.default)(instance._destinationPath, queueInstanceName);
}
finally {
_d = true;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (!_d && !_a && (_b = instances_2.return)) yield _b.call(instances_2);
}
finally { if (e_2) throw e_2.error; }
}
});
}
generateMiddlewares(instancePath, instanceName) {
var _a, e_3, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
const instances = this.getInstances();
if (instances.length <= 0) {
console.error('> No events plugin found, skipping build...');
return;
}
let finalCode = ``;
try {
for (var _d = true, instances_3 = __asyncValues(instances), instances_3_1; instances_3_1 = yield instances_3.next(), _a = instances_3_1.done, !_a;) {
_c = instances_3_1.value;
_d = false;
try {
const instance = _c;
// create a file index.js
finalCode = finalCode.concat(`
const userCustomMiddlewares = require("./middleware");\n
const ServerSDK = require("../Context.ts");
function createNext(serverSDK, next) {
return next.bind(serverSDK._ctx)
}
module.exports.${instanceName}Middlewares = {
// Wrap local action handlers (legacy middleware handler)
localAction: (next, action) => {
for (let key in userCustomMiddlewares) {
if (action.name === key) {
return function (ctx) {
const serverSDK = new ServerSDK(ctx);
const customNext = createNext(serverSDK, next);
return userCustomMiddlewares[key](customNext, serverSDK);
};
}
}
return next;
},
remoteAction: (next, action) => {
for (let key in userCustomMiddlewares) {
if (action.name === key) {
return function (ctx) {
const serverSDK = new ServerSDK(ctx);
const customNext = createNext(serverSDK, next);
return userCustomMiddlewares[key](customNext, serverSDK);
};
}
}
return next;
},
};
`);
const middlewareFolderPath = (0, path_1.join)(instance._destinationPath, instanceName);
(0, helpers_1.writeFile)((0, path_1.join)(middlewareFolderPath, 'index.js'), finalCode);
// Add middlewares in moleculer.config.js
const moleculerConfigPath = (0, path_1.join)(instance._destinationPath, 'moleculer.config.js');
let moleculerConfig = (0, fs_1.readFileSync)(moleculerConfigPath, {
encoding: 'utf-8',
});
const importString = `const { ${instanceName}Middlewares } = require("./${instanceName}");`;
if (!moleculerConfig.includes(importString)) {
moleculerConfig = moleculerConfig.replace('/* User Custom Middleware Imports */', `const { ${instanceName}Middlewares } = require("./${instanceName}");
/* User Custom Middleware Imports */`);
moleculerConfig = moleculerConfig.replace('/* User Custom Middleware */', `${instanceName}Middlewares, /* User Custom Middleware */`);
}
yield (0, helpers_1.writeFile)(moleculerConfigPath, moleculerConfig);
}
finally {
_d = true;
}
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (!_d && !_a && (_b = instances_3.return)) yield _b.call(instances_3);
}
finally { if (e_3) throw e_3.error; }
}
});
}
generateCrons(cronInstancePath, cronInstanceName) {
return __awaiter(this, void 0, void 0, function* () {
const instances = this.getInstances();
if (instances.length <= 0) {
console.error('> No functions plugin found, skipping build');
return;
}
instances.forEach((instance) => __awaiter(this, void 0, void 0, function* () {
const targetPkgJson = (0, path_1.join)(instance._destinationPath, 'package.json');
if (yield (0, helpers_1.fileExists)(targetPkgJson)) {
let data = yield (0, read_file_1.default)(targetPkgJson);
data = JSON.parse(data);
if (!data.devDependencies) {
data.devDependencies = {};
}
data.devDependencies['moleculer-cron'] = 'latest';
data.devDependencies.axios = 'latest';
const stringData = JSON.stringify(data, null, 2);
yield fs_1.default.writeFileSync(targetPkgJson, stringData);
(0, print_1.success)("We have added moleculer-cron to your service-gateway package.json\n Please run 'npm install' to install the package\n and restart your service-gateway instance \n");
}
else {
(0, print_1.warning)('We could not find the package.json for service-gateway instance\n Please add moleculer-cron to your service-gateway package.json\n and restart your service-gateway instance \n');
}
yield (0, write_cron_service_1.default)(cronInstancePath, instance._destinationPath, cronInstanceName);
}));
});
}
generateEventsService() {
return __awaiter(this, void 0, void 0, function* () {
const instances = this.getInstances();
if (instances.length <= 0) {
console.error('> No functions plugin found, skipping build');
return;
}
instances.forEach((instance) => __awaiter(this, void 0, void 0, function* () {
const destination = (0, path_1.join)(instance._destinationPath, 'services', 'events.service.js');
(0, helpers_1.writeFile)(destination, (0, template_1.eventsTemplate)());
}));
});
}
generateDbClientService(cronInstanceName) {
return __awaiter(this, void 0, void 0, function* () {
const instances = this.getInstances();
if (instances.length <= 0) {
console.error('> No service gateway plugin found, skipping...');
return;
}
instances.forEach((instance) => __awaiter(this, void 0, void 0, function* () {
const targetPkgJson = (0, path_1.join)(instance._destinationPath, 'package.json');
if (yield (0, helpers_1.fileExists)(targetPkgJson)) {
const data = yield (0, read_file_1.default)(targetPkgJson);
// data = data;
if (!data.dependencies) {
data.dependencies = {};
}
data.dependencies.prisma = 'latest';
data.dependencies['@prisma/client'] = 'latest';
const stringData = JSON.stringify(data, null, 2);
yield fs_1.default.writeFileSync(targetPkgJson, stringData);
(0, print_1.success)("We have added prisma & @prisma/client to your service-gateway package.json\n Please run 'npm install' to install the package\n and restart your service-gateway instance \n");
}
else {
(0, print_1.warning)('We could not find the package.json for service-gateway instance\n Please add prisma & @prisma/client to your service-gateway package.json\n and restart your service-gateway instance \n');
}
yield (0, write_db_client_service_1.default)(instance._destinationPath, cronInstanceName);
}));
});
}
generateStorageClientService(storageClientInstanceName) {
var _a, e_4, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
if (this.instances.length === 0) {
return;
}
const plugin = this.app.getPluginByName('@gluestack-v2/glue-plugin-storage');
const storageInstances = plugin.getInstances();
const instances = this.getInstances();
try {
for (var _d = true, instances_4 = __asyncValues(instances), instances_4_1; instances_4_1 = yield instances_4.next(), _a = instances_4_1.done, !_a;) {
_c = instances_4_1.value;
_d = false;
try {
const instance = _c;
const targetPkgJson = (0, path_1.join)(instance._destinationPath, 'package.json');
if (yield (0, helpers_1.fileExists)(targetPkgJson)) {
const data = yield require(targetPkgJson);
if (!data.devDependencies) {
data.devDependencies = {};
}
// hard-coded the version here
data.devDependencies.minio = 'latest';
const stringData = JSON.stringify(data, null, 2);
fs_1.default.writeFileSync(targetPkgJson, stringData);
(0, print_1.success)("We have added minio to your service-gateway package.json\n Please run 'npm install' to install the package\n and restart your service-gateway instance \n");
}
else {
(0, print_1.warning)('We could not find the package.json for service-gateway instance\n Please add minio to your service-gateway package.json\n and restart your service-gateway instance \n');
}
(0, writeMinioStorageService_1.writeMinioStorageService)(instance._destinationPath, storageClientInstanceName, storageInstances[0]);
}
finally {
_d = true;
}
}
}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {
try {
if (!_d && !_a && (_b = instances_4.return)) yield _b.call(instances_4);
}
finally { if (e_4) throw e_4.error; }
}
});
}
}
exports.GlueStackPlugin = GlueStackPlugin;
});