Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module.exports = (context, callback) => {
- var data = JSON.parse(context.body);
- console.log("============");
- console.log(data);
- console.log(typeof data);
- run(data);
- callback
- .status(200)
- .succeed("job done");
- };
- const fs = require("fs");
- const Binary = require("mongodb").Binary;
- const fetch = require("node-fetch");
- // MongoDB connection for schema files.
- const MongoClient = require("mongodb").MongoClient;
- //#### CUSTOM MODULE IMPORT ####
- var cli = require("./helper.js");
- //#### ENVIRONMENT VARIABLE ####
- //MongoDB Credential
- const MONGO_URL = "mongodb://prisma:password@35.185.183.19:443/PrismaDB";
- const MONGO_DB = "PrismaDB";
- const MONGO_COLLECTION = "prisma";
- //GitHub Credential
- const GITHUB_URL = "https://api.github.com/repos/shah05/tutorials/contents/";
- const GITHUB_USER = "shah05";
- const GITHUB_EMAIL = "alipitchay2006@gmail.com";
- // GitHub Personal Token
- var headers = {
- "Content-Type": "application/json",
- Authorization: "token f633936b5ff929b6a0ba2a58a96ee1cdec45cc56"
- };
- function run({ hostname, dbName, dbType, port, username, password }) {
- //1. Extract data db credentials from JSON body.
- console.log(hostname, dbName, username, password, dbType, port);
- console.log("==========================>");
- //2. Check if the schema file of this DB exist in MongoDB.(i.e DB has been introspected previously)
- schemaId = hostname + "_" + dbName;
- try {
- //3. Connect to mongoDB
- MongoClient.connect(MONGO_URL, (err, client) => {
- if (err) return console.log(err);
- const db = client.db(MONGO_DB);
- // client.close();
- //Promise to query MongoDB based on schemaIdls
- var myPromise = () => {
- return new Promise((resolve, reject) => {
- //MongoDB query.
- db.collection(MONGO_COLLECTION)
- .find({ schemaid: schemaId })
- .limit(1)
- .toArray(function(err, data) {
- if (err) reject(err);
- else {
- resolve(data[0]);
- //Close MongoDB connection
- client.close();
- }
- // err ? reject(err) : resolve(data[0]);
- });
- });
- };
- var n = new Date();
- //Pre 4. create folder
- cli.execute("sh function/start_introspect.sh " + n.toISOString() + "_" + hostname).then(result => {
- console.log(result, " - start_introspect");
- var prisma_project = "/tmp/" + n.toISOString() + "_" +hostname + "_prisma";
- //4. Trigger the promise and check result of MongoDB query.
- myPromise().then(result => {
- //5. If schema file exist in DB, parse the content and return table names/column name/type names.
- if (typeof result != "undefined") {
- console.log("found");
- // console.log(result.schemacontent.buffer);
- // Write content to schema.prisma file.
- fs.writeFileSync(
- prisma_project + "/schema.prisma",
- result.schemacontent.buffer,
- function(err) {
- if (err) throw err;
- console.log("Successfully saved");
- }
- );
- //Call existing_schema.sh script to parse and return tableName, columnName, typeName.
- cli.execute("sh "+ prisma_project + "/existing_schema.sh " + prisma_project).then(result => {
- console.log(result, "@@@@@@@@@@");
- console.log("------------- ================ -------------");
- console.log(retrieveTableColNames(result));
- // res.json(retrieveTableColNames(result));
- });
- } else {
- // 6. If schema file does not exist in DB, perform introspect via PrismaCLI, push schema file to MongoDB and push Photon API script to Github
- console.log("not found");
- // Call new_schema.sh script to parse and return tableName, columnName and typeName
- console.log("ENV====>", username, password, hostname, port, dbName);
- console.log(
- "/bin/sh " + prisma_project + "/new_schema.sh " +
- username +
- " " +
- password +
- " " +
- hostname +
- " " +
- port +
- " " +
- dbName +
- " " +
- prisma_project
- )
- cli
- .execute(
- "/bin/sh " + prisma_project + "/new_schema.sh " +
- username +
- " " +
- password +
- " " +
- hostname +
- " " +
- port +
- " " +
- dbName +
- " " +
- prisma_project
- )
- .then(result => {
- console.log("RESULT =================");
- console.log(result);
- console.log("RESULT =================");
- //Call function to transform output from bash script to JSON.
- console.log(retrieveTableColNames(result));
- //Call function to push schema.prisma file to MongoDB.
- MongoClient.connect(MONGO_URL, (err, client) => {
- const db = client.db(MONGO_DB);
- pushSchemaToDB(hostname, dbName, db, prisma_project, n);
- client.close();
- });
- //Execute script to generate Photon API and call function to push to GitHub
- cli
- .execute(
- "sh " + prisma_project + "/generate_api.sh " + hostname + " " + dbName + " " + prisma_project
- )
- .then(result => {
- pushToGitHub(hostname + "_" + dbName, prisma_project, n);
- });
- });
- }
- });
- });
- });
- } catch (error) {
- console.log("ERROR: ", error);
- }
- }
- function retrieveTableColNames(scriptOutput) {
- scriptOutput = scriptOutput.trim();
- console.log(scriptOutput)
- data = scriptOutput.split("|");
- tableNames = data[0].split(" ");
- colNames = data[1].split(" ");
- typeNames = data[2].split(" ");
- final_res = [];
- for (let i = 0; i < tableNames.length; i++) {
- index = -1;
- col = [];
- for (let j = 0; j < colNames.length; j++) {
- // Update idIndex everytime "model" is detected. (indicates the start of column names for a given table).
- if (colNames[j] == "model") {
- index += 1;
- }
- //only push when id is same i so that the col names are associated to the correct table names.
- if (index == i) {
- // Exclude "model" as column names.
- if (colNames[j] !== "model") {
- //Create object
- colType = {
- name: colNames[j],
- type: typeNames[j]
- };
- col.push(colType);
- }
- }
- }
- //construct json object and push in list.
- tableData = {
- table: tableNames[i],
- columns: col
- };
- final_res.push(tableData);
- }
- return JSON.stringify(final_res);
- }
- function pushToGitHub(apiFileName, prisma_project, n) {
- url = GITHUB_URL + n.toISOString() + "_" + apiFileName;
- var fileContent = fs.readFileSync(prisma_project + "/node_modules/@prisma/client/index.js", {
- // <<<<<<<<<<<<<<<<<<< not being updated
- encoding: "base64"
- });
- var data = {
- message: "update file",
- committer: {
- name: GITHUB_USER,
- email: GITHUB_EMAIL
- },
- content: fileContent
- };
- var jsonData = JSON.stringify(data);
- //REST Call to update in GitHub
- fetch(url, { method: "PUT", headers: headers, body: jsonData })
- .then(res => {
- console.log("FINAL---- PUSHED TO GITHUB-----------", res);
- })
- .then(json => {
- console.log(json);
- // Do something with the returned data.
- });
- }
- function pushSchemaToDB(hostname, dbName, db, prisma_project, n) {
- var data = fs.readFileSync(prisma_project + "/schema.prisma");
- var insert_data = {};
- insert_data = Binary(data);
- //schema file object
- schemaFile = {
- schemaid: n.toISOString() + "_" + hostname + "_" + dbName,
- schemacontent: insert_data
- };
- var collection = db.collection(MONGO_COLLECTION);
- collection.insert(schemaFile, function(err, result) {
- if (err) return console.log(err);
- });
- }
- // run({
- // hostname: "192.168.68.8",
- // dbName: "Company",
- // dbType: "mysql",
- // port: "3308",
- // username: "root",
- // password: "root"
- // });
- // run({
- // hostname: "192.168.68.8",
- // dbName: "shahidan",
- // dbType: "mysql",
- // port: "3306",
- // username: "root",
- // password: "root"
- // });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement