@gapi/cli
Version:
Gapi command line interface
186 lines (184 loc) • 10.3 kB
JavaScript
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SchemaTask = void 0;
const compressor_1 = require("@rxdi/compressor");
const core_1 = require("@rxdi/core");
const fs_1 = require("fs");
const node_fetch_1 = require("node-fetch");
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
const util_1 = require("util");
const helpers_1 = require("../core/helpers");
const mkdirp_1 = require("../core/helpers/mkdirp");
const args_service_1 = require("../core/services/args.service");
const config_service_1 = require("../core/services/config.service");
const exec_service_1 = require("../core/services/exec.service");
const daemon_config_1 = require("../daemon-server/daemon.config");
let SchemaTask = class SchemaTask {
constructor() {
this.execService = core_1.Container.get(exec_service_1.ExecService);
this.argsService = core_1.Container.get(args_service_1.ArgsService);
this.configService = core_1.Container.get(config_service_1.ConfigService);
}
run(introspectionEndpoint, introspectionOutputFolder, pattern) {
return __awaiter(this, void 0, void 0, function* () {
const originalConsole = console.log.bind(console);
console.log = function () {
const cwd = process.cwd().split('/');
return originalConsole.apply(console, [
'\x1b[36m%s\x1b[0m',
`${cwd[cwd.length - 1]} =>`,
...arguments,
]);
};
this.folder =
introspectionOutputFolder ||
this.configService.config.config.schema.introspectionOutputFolder;
this.endpoint =
introspectionEndpoint ||
this.configService.config.config.schema.introspectionEndpoint;
this.pattern = pattern || this.configService.config.config.schema.pattern;
this.node_modules = __dirname.replace('dist/tasks', 'node_modules');
this.bashFolder = __dirname.replace('dist/tasks', 'bash');
this.headers = this.configService.config.config.schema.headers;
if (process.argv[3] === 'introspect') {
yield this.createDir();
yield this.generateSchema();
}
if (process.argv[3] === 'collect' ||
this.argsService.args.includes('--collect-documents')) {
yield this.createDir();
yield this.collectQueries();
yield this.collectFragments();
}
console.log(`[Final] To change export folder for this command you need to check this link https://github.com/Stradivario/gapi-cli/wiki/schema`);
});
}
createDir() {
return __awaiter(this, void 0, void 0, function* () {
if (!(yield (0, util_1.promisify)(fs_1.exists)(this.folder))) {
yield (0, util_1.promisify)(mkdirp_1.mkdirp)(this.folder);
}
yield (0, util_1.promisify)(mkdirp_1.mkdirp)(daemon_config_1.GAPI_DAEMON_CACHE_FOLDER);
});
}
collectFragments() {
return __awaiter(this, void 0, void 0, function* () {
console.log('[CollectFragments]: fragments collection started');
return (0, rxjs_1.from)((0, node_fetch_1.default)(this.endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
variables: {},
query: `
{
__schema {
types {
kind
name
possibleTypes {
name
}
}
}
}
`,
}),
}))
.pipe((0, operators_1.switchMap)((res) => res.json()), (0, operators_1.map)((res) => res.data), (0, operators_1.switchMap)(({ __schema }) => {
// here we're filtering out any type information unrelated to unions or interfaces
const filteredData = __schema.types.filter((type) => type.possibleTypes !== null);
__schema.types = filteredData;
return (0, util_1.promisify)(fs_1.writeFile)(`${this.folder}/fragmentTypes.ts`, `/* tslint:disable */
/* eslint-disable prettier/prettier */
export const introspectionQueryResultData = ${JSON.stringify({ __schema }, null, 2)}
`);
}), (0, operators_1.tap)(() => console.log('[CollectFragments]: fragments collection finished')))
.toPromise();
});
}
collectQueries() {
return __awaiter(this, void 0, void 0, function* () {
console.log('[CollectQueries]: queries collection started');
const randomString = Math.random().toString(36).substring(2);
console.log(`[CollectQueries]: generating temporary documents file ${daemon_config_1.GAPI_DAEMON_CACHE_FOLDER}/${randomString}.json`);
yield this.execService.call(`node ${this.node_modules}/graphql-document-collector/bin/graphql-document-collector '${this.pattern ? this.pattern : '**/*.{graphql,gql}'}' > ${daemon_config_1.GAPI_DAEMON_CACHE_FOLDER}/${randomString}.json`);
console.log(`[CollectQueries]: reading temporary documents file ${daemon_config_1.GAPI_DAEMON_CACHE_FOLDER}/${randomString}.json`);
const readDocumentsTemp = yield (0, util_1.promisify)(fs_1.readFile)(`${daemon_config_1.GAPI_DAEMON_CACHE_FOLDER}/${randomString}.json`, 'utf-8');
yield (0, util_1.promisify)(fs_1.unlink)(`${daemon_config_1.GAPI_DAEMON_CACHE_FOLDER}/${randomString}.json`);
if (this.argsService.args.includes('--collect-types')) {
console.log(`[CollectQueries]: generating types`);
yield this.generateTypes(readDocumentsTemp);
}
const parsedDocuments = `/* tslint:disable */\n/* eslint-disable prettier/prettier */ \nexport const DOCUMENTS = ${readDocumentsTemp};`;
console.log(`[CollectQueries]: writing file to disc ${this.folder}/documents.ts`);
yield (0, util_1.promisify)(fs_1.writeFile)(`${this.folder}/documents.ts`, parsedDocuments, 'utf8');
if (this.argsService.args.includes('--with-compressed')) {
yield (0, util_1.promisify)(fs_1.writeFile)(`${this.folder}/documents.compressed.ts`, 'export const DocumentsCompressed = `' +
compressor_1.LZWService.compress(JSON.parse(readDocumentsTemp)) +
'`', 'utf8');
}
console.log('[CollectQueries]: queries collection finished');
});
}
generateSchema() {
return __awaiter(this, void 0, void 0, function* () {
console.log(`[GenerateSchema]: Trying to hit ${this.endpoint} ...`);
yield this.execService.call(`${(0, helpers_1.isWindows)() ? 'set' : 'export'} NODE_TLS_REJECT_UNAUTHORIZED=0 && node ${this.node_modules}/apollo-codegen/lib/cli.js introspect-schema ${this.endpoint} ${this.headers ? `--header "${this.headers}"` : ''} --output ${this.folder}/schema.json`);
console.log(`[GenerateSchema]: Endpoint ${this.endpoint} hit!`);
yield this.execService.call(`${(0, helpers_1.isWindows)() ? 'set' : 'export'} NODE_TLS_REJECT_UNAUTHORIZED=0 && node ${this.bashFolder}/gql2ts/index.js ${this.folder}/schema.json -o ${this.folder}/index.ts`);
console.log(`[GenerateSchema]: Typescript interfaces generated inside folder: ${this.folder}/index.d.ts`);
});
}
generateTypes(readDocumentsTemp) {
return __awaiter(this, void 0, void 0, function* () {
const savedDocuments = Object.keys(JSON.parse(readDocumentsTemp))
.map((key) => {
const n = key.lastIndexOf('/');
const result = key.substring(n + 1);
if (result === 'ListMovies.graphql') {
return;
}
if (result === 'Place.graphql') {
return;
}
if (result === 'Movie.graphql') {
return;
}
return result;
})
.filter((i) => !!i);
const types = `/* eslint-disable prettier/prettier */
function strEnum<T extends string>(o: Array<T>): { [K in T]: K } {
return o.reduce((res, key) => {
res[key] = key;
return res;
}, Object.create(null));
}
export const DocumentTypes = strEnum(${JSON.stringify(savedDocuments)
.replace(/"/g, `'`)
.replace(/,/g, ',\n')});
export type DocumentTypes = keyof typeof DocumentTypes;`;
return yield (0, util_1.promisify)(fs_1.writeFile)(`${this.folder}/documentTypes.ts`, types, 'utf8');
});
}
};
exports.SchemaTask = SchemaTask;
exports.SchemaTask = SchemaTask = __decorate([
(0, core_1.Service)()
], SchemaTask);