Skip to content

Commit

Permalink
Add requests log in debug mode
Browse files Browse the repository at this point in the history
  • Loading branch information
evg-evdokimov committed Aug 14, 2023
1 parent c7cab18 commit 74f08e3
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
4 changes: 4 additions & 0 deletions bin/vk-miniapps-deploy
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ async function run() {
const deploy = require('../index');
const cfg = configJSON || {};

if (cfg.debug) {
console.log('\nDebug mode is enabled. It will log all client requests!\n');
}

let confirmation = {
result: true,
}
Expand Down
40 changes: 39 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const crypto = require('crypto');
const packageJson = require('./package.json');
const chalk = require('chalk');
const prompt = require('prompts');
const fetch = require('node-fetch');
const nodeFetch = require('node-fetch');
const { zip } = require('zip-a-folder');
const fs = require('fs-extra');
const FormData = require('form-data');
Expand All @@ -14,6 +15,8 @@ var cfg = configJSON || {};
prompt.message = "vk-mini-apps-deploy".grey;
prompt.delimiter = "=>".grey;

const DEBUG_MODE = !!cfg.debug;

const API_HOST = cfg.api_host || 'https://api.vk.com/method/';
const OAUTH_HOST = cfg.oauth_host || 'https://oauth.vk.com/';

Expand Down Expand Up @@ -63,6 +66,41 @@ const URL_NAMES_MAP = {
[URL_NAMES.MOBILE_WEB]: PLATFORMS.MOBILE_WEB,
};

function getTraceId() {
return crypto.randomBytes(4).toString("hex");
}

/**
* @param {nodeFetch.RequestInfo} url
* @param {nodeFetch.RequestInit} options
* @returns {Promise<nodeFetch.Response>}
*/
async function fetch(url, options) {
if (!DEBUG_MODE) {
return nodeFetch(url, options);
}

const traceId = chalk.hex(`#${(Math.random() * 0xFFFFFF << 0).toString(16)}`)(getTraceId());
const logLine = (line, type) => console.log(`[${traceId}][${type}]`, chalk.cyan(line));
const logError = (error) => console.error(`[${traceId}][ERROR]`, chalk.red(error));

try {
logLine(url, 'REQ');
options && logLine(JSON.stringify(options), 'REQ');

const response = await nodeFetch(url, options);
const body = await response.clone().text();

logLine(`${response.status} ${response.statusText}`, 'RESP');
logLine(body, 'RESP');

return response
} catch (e) {
logError(e);
throw e;
}
}

async function auth() {
const get_auth_code = await fetch(OAUTH_HOST + 'get_auth_code?scope=offline&client_id=' + DEPLOY_APP_ID);
const get_auth_code_res = await get_auth_code.json();
Expand Down
3 changes: 2 additions & 1 deletion vk-hosting-config.json.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@
"mvk": "index.html",
"web": "index.html",
"mobile": "index.html"
}
},
debug: false
}

0 comments on commit 74f08e3

Please sign in to comment.