Sails.JS winston always showing in JSON? - sails.js

I'm using Sails.JS for my web app and my log.js has the following:
const winston = require('winston');
const winstonRotate = require('winston-daily-rotate-file');
const path = require('path');
module.exports.log = {
level: 'silly',
colors: false,
custom: winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new (winston.transports.Console)({
level: 'info',
colorize: false,
json: false
}),
new (winstonRotate)({
filename: path.join(process.cwd(), "logs", "main"),
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d',
colorize: false,
'json': false,
})
]
})
};
The problem I have is that I clearly set no JSON and no colors but the console and the file still have them. What am I doing wrong? I've already checked these resources for this issue without success:
https://medium.com/#danielyewright/using-winston-for-logging-in-sailsjs-f9056d72e5e7
https://gist.github.com/barretts/ae7fff301168ef623611

I figured it out. I had to change format on the original post. I have it below:
module.exports.log = {
level: 'silly',
colors: false,
custom: winston.createLogger({
level: 'info',
format: winston.format.printf(info => {
return `${new Date().toISOString()}] ${info.level}: ${info.message}`;
}),
transports: [
new (winston.transports.Console)({
level: 'verbose',
colorize: false,
json: false
}),
new (winstonRotate)({
filename: path.join(process.cwd(), "logs", "main"),
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d',
colorize: false,
json: false,
})
]
})
};

Related

What should the publicPath in webpack config be for a dynamic port?

I'm currently building a microfrontend using webpack's module federation, however when I create a deployment in kubernetes it's not resolving because of an incorrect publicPath. It's still a bit complex to me and I'm not sure what to set the publicPath to as the localhost port keeps changing every deployment.
So it looks like: http://127.0.0.1:TUNNEL_PORT, whereby TUNNEL_PORT is dynamic. How would I account for this when defining my output.publicPath?
Webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const deps = require("./package.json").dependencies;
module.exports = {
output: {
publicPath: "http://localhost:3000/",
// publicPath: 'auto',
},
resolve: {
extensions: [".tsx", ".ts", ".jsx", ".js", ".json"],
},
devServer: {
port: 3000,
historyApiFallback: true,
},
module: {
rules: [
{
test: /\.m?js/,
type: "javascript/auto",
resolve: {
fullySpecified: false,
},
},
{
test: /\.(css|s[ac]ss)$/i,
use: ["style-loader", "css-loader", "postcss-loader"],
},
{
test: /\.(ts|tsx|js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
],
},
plugins: [
new ModuleFederationPlugin({
name: "microfrontend1",
filename: "remoteEntry.js",
remotes: {},
exposes: {
"./Header": "./src/Header.tsx",
"./Footer": "./src/Footer.tsx",
},
shared: {
...deps,
react: {
singleton: true,
eager: true,
requiredVersion: deps.react,
},
"react-dom": {
singleton: true,
eager: true,
requiredVersion: deps["react-dom"],
},
},
}),
new HtmlWebPackPlugin({
template: "./src/index.html",
}),
],
};

Server side error while executing the script in appium

I was trying to execute the appium script in an virtual emulator.But while executing i am getting this below error.In emulator the app is launched but it doesn't perform any action gets closed.
Error:-
[16:52:46] E/launcher - An unknown server-side error occurred while processing the command. Original error: No Chromedriver found that can automate Chrome '77.0.3865'. See https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/web/chromedriver.md for more details. You could also try to enable automated chromedrivers download server feature
[16:52:46] E/launcher - WebDriverError: An unknown server-side error occurred while processing the command. Original error: No Chromedriver found that can automate Chrome '77.0.3865'. See https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/web/chromedriver.md for more details. You could also try to enable automated chromedrivers download server feature
[16:52:46] E/launcher - Process exited with error code 199
Conf File:-
const { SpecReporter } = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 300000,
seleniumAddress: 'http://localhost:4723/wd/hub',
specs: [
'./e2e/**/login.mobile.ts',
],
useAllAngular2AppRoots: true,
//chromeDriver: './node_modules/chromedriver/lib/chromedriver/chromedriver.exe',
capabilities: {
platformName: 'Android',
platformVersion: '9',
deviceName: 'emulator-5554',
browserName: '',
appiumVersion:'1.16.0',
autoWebview: true,
autoWebviewTimeout: 10000,
autoacceptalerts: true,
autoGrantPermissions: true,
clearSystemFiles: true,
app: './platforms/android/build/outputs/apk/android-debug.apk
},
//baseUrl: 'http://10.0.2.2:8000',
plugins: [
{
path: require.resolve('protractor-console'),
logLevels: ['severe'],
package: 'jasmine2-protractor-utils',
disableHTMLReport: false,
disableScreenshot: false,
screenshotPath: './screenshots',
screenshotOnExpectFailure: true,
screenshotOnSpecFailure: true,
clearFoldersBeforeTest: true
}
],
// directConnect: true, //enable for desktop
//baseUrl: 'http://localhost:4723/wd/hub',
framework: 'jasmine2',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 300000,
print: function() {}
},
beforeLaunch: function() {
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
});
},
onPrepare() {
var jasmineReporters = require('jasmine-reporters');
jasmine.getEnv().addReporter(
new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: './report/mobile',
filePrefix: 'xmlresults'
})
);
var wd = require('wd'),
protractor = require('protractor'),
wdBridge = require('wd-bridge')(protractor, wd);
wdBridge.initFromProtractor(exports.config);
},
onComplete: function() {
var browserName, browserVersion;
var capsPromise = browser.getCapabilities();
capsPromise.then(function(caps) {
browserName = caps.get('browserName');
browserVersion = caps.get('version');
var HTMLReport = require('protractor-html-reporter');
testConfig = {
reportTitle: 'CVM Test Execution Report',
outputPath: './report/mobile', //relative path
screenshotPath: './screenshots',
testBrowser: 'Mobile',
browserVersion: browserVersion,
modifiedSuiteName: false,
screenshotsOnlyOnFailure: true
};
new HTMLReport().from('./report/mobile/xmlresults.xml', testConfig);
});
}
};

How to upload local image to facebook

I managed to upload an image to facebook using online URL but, when I try a local image using format file://path/to/imageI get the error
{"error":{"message":"(#100) url should represent a valid URL","type":"OAuthException","code":100}
is it doable ? or am doing it wrong ?
async function upload_fb_image(photo) {
return new Promise(resolve => {
FB.api(PAGE_ID + '/photos', 'post', {
message: 'Message',
url: LINK_TO_IMAGE,
published: false,
caption: 'Ad',
access_token: EXD_ACCESS_TOKEN
}).then(data => { resolve(data) })
})
}
as Form data
I tried as form data as mentioned in answers ... I receive ok response but, the image ID is not returned, I get the below JSON in reponse
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]:
{ body:
PassThrough {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: [Object], tail: [Object], length: 1 },
length: 25,
pipes: null,
pipesCount: 0,
flowing: null,
ended: true,
endEmitted: false,
reading: false,
sync: false,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
paused: true,
emitClose: true,
autoDestroy: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
_events:
[Object: null prototype] {
prefinish:
{ [Function: prefinish]
[length]: 0,
[name]: 'prefinish',
[prototype]: prefinish { [constructor]: [Circular] } },
error:
{ [Function]
[length]: 1,
[name]: '',
[prototype]: { [constructor]: [Circular] } } },
_eventsCount: 2,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: true,
ended: true,
finished: true,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite:
{ [Function: bound onwrite] [length]: 1, [name]: 'bound onwrite' },
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: true,
errorEmitted: false,
emitClose: true,
autoDestroy: false,
bufferedRequestCount: 0,
corkedRequestsFree:
{ next: null,
entry: null,
finish:
{ [Function: bound onCorkedFinish] [length]: 1, [name]: 'bound onCorkedFinish' } } },
writable: false,
allowHalfOpen: true,
_transformState:
{ afterTransform:
{ [Function: bound afterTransform] [length]: 2, [name]: 'bound afterTransform' },
needTransform: false,
transforming: false,
writecb: null,
writechunk: null,
writeencoding: 'buffer' } },
disturbed: false,
error: null },
[Symbol(Response internals)]:
{ url: 'https://graph.facebook.com/page_id/photos',
status: 200,
statusText: 'OK',
headers:
Headers {
[Symbol(map)]:
[Object: null prototype] {
'x-business-use-case-usage':
[ '{"1006471116044666":[{"type":"pages","call_count":1,"total_cputime":1,"total_time":1,"estimated_time_to_regain_access":0}]}',
[length]: 1 ],
'content-type': [ 'application/json; charset=UTF-8', [length]: 1 ],
'facebook-api-version': [ 'v2.10', [length]: 1 ],
'strict-transport-security': [ 'max-age=15552000; preload', [length]: 1 ],
pragma: [ 'no-cache', [length]: 1 ],
'x-fb-rev': [ '1001316471', [length]: 1 ],
'access-control-allow-origin': [ '*', [length]: 1 ],
'cache-control':
[ 'private, no-cache, no-store, must-revalidate', [length]: 1 ],
'x-fb-trace-id': [ 'CSSaQru0iZZ', [length]: 1 ],
'x-fb-request-id': [ 'AguAWIpbfPySfVvwPjZZBec', [length]: 1 ],
expires: [ 'Sat, 01 Jan 2000 00:00:00 GMT', [length]: 1 ],
'x-fb-debug':
[ 'NnSTSun7s8VUcMnXu9cUYXQh/7laST0pILTNbAJrS0mtGHGXnQt17fRtyhS8R+RkZWyawJ4meKDWNKT1N+1uBA==',
[length]: 1 ],
date: [ 'Sat, 19 Oct 2019 01:31:32 GMT', [length]: 1 ],
'x-fb-trip-id': [ '1886706526', [length]: 1 ],
'alt-svc': [ 'h3-23=":443"; ma=3600', [length]: 1 ],
connection: [ 'close', [length]: 1 ],
'content-length': [ '25', [length]: 1 ] } },
counter: 0 } }
The url must be a public url, not some url from your local computer. Alternatively, you can use FormData:
const fileReader = new FileReader();
const file = document.getElementById('imageInput').files[0];
fileReader.onloadend = async () => {
const photoData = new Blob([fileReader.result], {type: 'image/jpg'});
const formData = new FormData();
formData.append('access_token', pageAccessToken);
formData.append('source', photoData);
formData.append('message', 'some status message');
let response = await fetch(`https://graph.facebook.com/${pageId}/photos`, {
body: formData,
method: 'post'
});
response = await response.json();
console.log(response);
};
fileReader.readAsArrayBuffer(file);
Source: https://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-with-formdata/
finally it was solved using the below method
const formData = {
access_token: EXD_ACCESS_TOKEN,
source: fs.createReadStream("path/to/image"),
published: 'false'
}
console.log('sendning request')
request.post({ url: `https://graph.facebook.com/${PAGE_ID}/photos`, formData: formData }, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
resolve(body)
});

Sequelize Migration addIndex not adding index in descending order

I am trying to create an index on an existing table (Postgres) on a date column so that I can get the latest posts first
Model file feeditem.js
module.exports = (sequelize, DataTypes) => {
const FeedItem = sequelize.define('FeedItem', {
feedItemId: {
//...
},
pubdate: {
allowNull: false,
type: DataTypes.DATE,
validate: {
isDate: true,
notEmpty: true,
},
},
link: {
//...
},
title: {
//...
},
description: {
//...
},
summary: {
//...
},
author: {
//...
},
hash: {
//...
},
}, {
timestamps: false,
underscored: true,
indexes: [
{
fields: [{ attribute: 'pubdate', order: 'DESC' }],
unique: false,
},
],
});
FeedItem.associate = (models) => {
// associations can be defined here
//...
};
return FeedItem;
};
Migration file create-feed-item.js
module.exports = {
up: (queryInterface, Sequelize) => queryInterface.createTable('feed_items', {
feed_item_id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
pubdate: {
allowNull: false,
type: Sequelize.DATE,
},
link: {
allowNull: false,
type: Sequelize.STRING,
},
title: {
allowNull: false,
type: Sequelize.STRING,
},
description: {
type: Sequelize.TEXT,
},
summary: {
type: Sequelize.TEXT,
},
author: {
type: Sequelize.STRING,
},
hash: {
allowNull: false,
type: Sequelize.UUID,
unique: true,
},
}),
// eslint-disable-next-line no-unused-vars
down: (queryInterface, Sequelize) => queryInterface.dropTable('feed_items'),
};
Migration file add-index.js
module.exports = {
/*
Add altering commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.createTable('users', { id: Sequelize.INTEGER });
*/
// eslint-disable-next-line no-unused-vars
up: (queryInterface, Sequelize) => queryInterface.addIndex('feed_items', ['pubdate'], {
fields: [{
attribute: 'pubdate', order: 'DESC',
}],
unique: false,
name: 'feed_items_pubdate_index',
}),
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.dropTable('users');
*/
// eslint-disable-next-line no-unused-vars
down: (queryInterface, Sequelize) => queryInterface.removeIndex('feed_items', 'feed_items_pubdate_index'),
};
The migrations are run in perfect order where table is created first and index is added later.
Logging is enabled and when I check the logs
Expected:
It should create a DESC index on pubdate which goes like
CREATE INDEX "feed_items_pubdate_index" ON "feed_items" ("pubdate" DESC)
Actual Output
Executing (default): CREATE INDEX "feed_items_pubdate_index" ON "feed_items" ("pubdate")
Any ideas what is going wrong here?
Your question is still relevant because it is undocumented.
The proper way to define index in descending order is extended definition in fields argument.
So the migration file add-index.js should look like:
module.exports = {
...
up: (queryInterface, Sequelize) => queryInterface.addIndex(
'feed_items',
[{
attribute: 'pubdate', order: 'DESC',
}],
{
unique: false,
name: 'feed_items_pubdate_index',
}
),
...
};
Resolved issue reference.
use uniqueKeys:
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
allowNull: true,
type: Sequelize.STRING
},
order: {
allowNull: false,
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
},
{
uniqueKeys: {
actions_unique: {
fields: ["name", "order"],
},
},
}
);
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Users');
}
};

How to generate multiple cucumber reports for protractor with multicapabilities?

I am running protractor against BrowserStack with multiple browser in parallel. Please refer to 'Speed up testing section in 'https://www.browserstack.com/automate/protractor.
It works great, however if I use 4 instances of webdriver to run the same feature files in parallel, it will 1 html cucumber report.
I've googled this: https://github.com/wswebcreation/protractor-multiple-cucumber-html-reporter-plugin, which seems to be able to generate multiple json file, but no html files.
I am new to protractor. Could anyone give some suggestions, or some code change or plugin that can make this happen?
Thank,
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
var JasmineReporters = require('jasmine-reporters');
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
framework: 'jasmine2',
multiCapabilities: [
{
browserName: 'chrome',
shardTestFiles: false,
maxInstances: 1,
specs: [
'./tmp/specs1.spec.js',
'./tmp/specs2.spec.js'
],
chromeOptions: {
args: [
'--window-size=1920,1080'],
prefs: {
download: {
prompt_for_download: false,
default_directory: './downloads',
}
}
}
},
{
browserName: 'chrome',
shardTestFiles: false,
maxInstances: 1,
specs: [
'./tmp/specs3.spec.js',
'./tmp/specs4.spec.js'
],
chromeOptions: {
args: [
'--window-size=1920,1080'],
prefs: {
download: {
prompt_for_download: false,
default_directory: './downloads',
}
}
}
}
],
allScriptsTimeout: 600000,
jasmineNodeOpts: {
defaultTimeoutInterval: 600000,
showColors: true
},
onPrepare: function() {
browser.driver.getCapabilities().then(function(caps) {
browser.browserName = caps.get('browserName');
});
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
browser.getProcessedConfig().then(function(config) {
var capabilities = config.capabilities;
jasmine.getEnv().addReporter(
new Jasmine2HtmlReporter({
savePath: './reports/',
takeScreenshots: true,
screenshotsFolder: './screenshots',
filePrefix: 'protractor-demo-tests-report-' + capabilities.platform + '-' + capabilities.browserName,
consolidateAll: false,
takeScreenshotsOnlyOnFailures: true,
})
);
});
var jasmineReporters = require('jasmine-reporters');
return browser.getProcessedConfig().then(function(config) {
// you could use other properties here if you want, such as platform and version
var browserName = config.capabilities.browserName;
var junitReporter = new jasmineReporters.JUnitXmlReporter({
consolidateAll: false,
savePath: 'reports/jUnitXmlReporter',
modifyReportFileName: function(generatedFileName, suite) {
return browserName + '.' + generatedFileName;
}
});
jasmine.getEnv().addReporter(junitReporter);
//set window size to max available
setTimeout(function() {
browser.driver.executeScript(function() {
return {
width: window.screen.availWidth,
height: window.screen.availHeight
};
}).then(function(result) {
browser.driver.manage().window().setPosition(0,0);
browser.driver.manage().window().setSize(result.width, result.height);
});
});
});
}
};