nodejs router docblock comment - router

I am writing below docblock for one of my app routers. Is it right?
also, tell me the meaning of each line as I don't know exactly.
/**
* Router serving Activity log page.
* #name get/activity_log
* #function
* #memberof module:routers/activity_log
* #inner
* #param {string} path - Activity log path
* #param {callback} middlewear - Express middlewear.
*/
router.get('/', function(req, res) {
var async = require('async');
var telemetry = require(modulePath)(req.dbquery,req.nosql);
telemetry.getTelemetryLog(function(err, data) {
console.log(data);
if(err) {
res.send(error);
} else {
res.render('_admin/activity_log', {
title: 'App Admin',
username: req.session.user.name,
notifications: req.session.notifications,
tasks: req.session.tasks,
telemetry: data
});
}
});
});

OK, as for the comments in upper part of code, they are docblock documentation parameters. You can use a documentation generator tool like JSDoc in case of Javascript, if it is meaningful to you.
You can find meaning of the tags like #name, #function, and others in links below:
http://usejsdoc.org/tags-name.html
http://usejsdoc.org/tags-function.html
http://usejsdoc.org/tags-inner.html
http://usejsdoc.org/tags-param.html
and so on.
After all code, or at least part is documented like that, you can generate a HTML content to browse your documentation clearly with hyperlinks.
To do this you need to install the JSDoc NPM package:
npm install -g jsdoc
Then you run the command line inside your main code directory indicating all you js files:
jsdoc *.js folder1/*.js folder2/*.js
This command will generate the HTML files for you code documentation in the out/ directory.
Open out/index.html to view the documentation.

Related

Cloudflare Worker template script error - country redirect

I grabbed example script from the Cloudflare GitHub worker example page for a simple country redirect. It fails and I don't know why? (I am not particularly strong in code stuff).
Error is:
Script modified; context reset. worker.js:17 Uncaught TypeError: Cannot read properties of undefined (reading 'country')
at redirect (worker.js:17)
at worker.js:28 redirect # worker.js:17 (anonymous) # worker.js:28 Uncaught (in response) TypeError: Cannot read properties of undefined (reading 'country')
The template code is:
/**
* A map of the URLs to redirect to
* #param {Object} countryMap
*/
const countryMap = {
US: "https://example.com/us",
EU: "https://eu.example.com/",
}
/**
* Returns a redirect determined by the country code
* #param {Request} request
*/
function redirect(request) {
// Use the cf object to obtain the country of the request
// more on the cf object: https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties
const country = request.cf.country
if (country != null && country in countryMap) {
const url = countryMap[country]
return Response.redirect(url)
} else {
return fetch(request)
}
}
addEventListener("fetch", event => {
event.respondWith(redirect(event.request))
})
From
https://github.com/cloudflare/cloudflare-docs/blob/production/products/workers/src/content/examples/country-code-redirect.md
Does anyone have advice on this? This is being run on the Cloudflare Workers system.
This is a known problem with the Worokers preview. request.cf is always undefined when using the embedded preview next to the editor. If you use wrangler dev to test your code instead, it will work correctly there, and it will also work once deployed.

Mistake in using DOMPurify on the backend to sanitize form data?

I was wondering if it was possible to use DOMPurify to sanitize user input on a form before it is saved to database. Here's what I've got in my routes.js folder for my form post:
.post('/questionForm', (req, res, next) =>{
console.log(req.body);
/*console.log(req.headers);*/
const questions = new QuestionForm({
_id: mongoose.Types.ObjectId(),
price: req.body.price,
seats: req.body.seats,
body_style: req.body.body_style,
personality: req.body.personality,
activity: req.body.activity,
driving: req.body.driving,
priority: req.body.priority
});
var qClean = DOMPurify.sanitize(questions);
//res.redirect(200, path)({
// res: "Message recieved. Check for a response later."
//});
qClean.save()
.then(result => {
//res.redirect(200, '/path')({
// //res: "Message recieved. Check for a response later."
//});
res.status(200).json({
docs:[questions]
});
})
.catch(err => {
console.log(err);
});
});
I also imported the package at the top of the page with
import DOMPurify from 'dompurify';
When I run the server and submit a post request, it throws a 500 error and claims that dompurify.sanitize is not a function. Am I using it in the wrong place, and/or is it even correct to use it in the back end at all?
This might be a bit late, but for others like me happening to run into this use case I found an npm package that seems well suited so far. It's called isomorphic-dompurify.
isomorphic-dompurify
DOMPurify needs a DOM to interact with; usually supplied by the browser. Isomorphic-dompurify feeds DOMPurify another package, "jsdom", as a dependency that acts like a supplementary virtual DOM so DOMPurify knows how to sanitize your input server-side.
In the packages' own words "DOMPurify needs a DOM tree to base on, which is not available in Node by default. To work on the server side, we need a fake DOM to be created and supplied to DOMPurify. It means that DOMPurify initialization logic on server is not the same as on client".
Building on #Seth Lyness's excellent answer --
If you'd rather not add another dependency, you can just use this code before you require DOMPurify. Basically what isometric-dompurify is doing is just creating a jsdom object and putting it in global.window.
const jsdom = require('jsdom');
const {JSDOM} = jsdom;
const {window} = new JSDOM('<!DOCTYPE html>');
global.window = window;

Is it possible to create a file with all my functions and read from from it in my specs?

I have some specs that are using the same functions, I would like to make one single file only for functions and read from this file while executing my scripts, would be that possible? if so.. how to do that?
During google searchers I found the "exports" to add in config file but didn't work (also I don't know how to call it from the config)
For example, I would like to add 2 functions in my config file (or separated file only for functions) and during any point of my execution, call it from the spec file:
function loginAdminUser(userElement, passWordElement, userName, password){
var loginButton = element(by.id('logIn'));
browser.get('https://( ͡° ͜ʖ ͡°).com/');
userElement.sendKeys(userName);
passWordElement.sendKeys(password);
loginButton.click();
}
function accessHistoryViewDetail(){
menuForViews.then(function(selectview) {
selectview[3].click();
browser.sleep(500);
});
}
1 - How can I do that? (using "Suites" would be an option?)
2 - How to call them in my specs?
Thank you and have a good day!
As far as I know you cannot add utility functions that you want to use in your tests in the config file. The options in the config file are generally for setting up the testing environment.
You can however put your functions in a separate file and import that to use the functions. Below is an example of how to do that using js and Node's module exports, you can do something similar with ts using classes.
// utils.js
function loginAdminUser(userElement, passWordElement, userName, password){
var loginButton = element(by.id('logIn'));
browser.get('https://( ͡° ͜ʖ ͡°).com/'); // nice Lenny face :)
userElement.sendKeys(userName);
passWordElement.sendKeys(password);
loginButton.click();
}
function accessHistoryViewDetail() {
menuForViews.then(function(selectview) {
selectview[3].click();
browser.sleep(500);
});
}
module.exports = {
loginAdminUserloginAdminUser: loginAdminUser,
accessHistoryViewDetail: accessHistoryViewDetail
}
Then in your spec file
import * as utils from './utils.js';
...
it('should ...', () => {
...
utils.accessHistoryViewDetail();
...
});
});
I hope that helps.

Is there a way to create and run a dynamic script from karma.conf.js

I'm using karma to run tests on an angularjs application.
There are a couple JavaScript functions that I would like to run at start-up, but they need to be dynamically created based on some system data. When running the app, this is handled with node.
Is there any way to create a script as a var and pass it to the files: [] rather than just using a pattern to load an existing file?
I can make this work by creating the file, saving it to disk then loading it normally, but that's messy.
You can create your own karma preprocessor script.
For a starting point use the following as example:
var fs = require('fs'),
path = require('path');
var createCustomPreprocessor = function (config, helper, logger) {
var log = logger.create('custom'),
// get here the configuration set in the karma.conf.js file
customConfig = config.customConfig || {};
// read more config here in case needed
...
// a preprocessor has to return a function that when completed will call
// the done callback with the preprocessed content
return function (content, file, done) {
log.debug('custom: processing "%s"\n', file.originalPath);
// your crazy code here
fs.writeFile(path.join(outputDirectory, name), ... , function (err) {
if (err) {
log.error(err);
}
done(content);
});
}
};
createCustomPreprocessor.$inject = ['config', 'helper', 'logger'];
module.exports = {
'preprocessor:custom': ['factory', createCustomPreprocessor]
};
Add a package.json with the dependencies and serve it as a module. ;)
For more examples have a look to more modules here: https://www.npmjs.org/search?q=karma%20preprocessor

Github: How to embed a gist into README.md?

Is it possible to embed gists into README.md file that resides in a GitHub repository?
Something like:
<code id="gist-3167145"></code>
No, sorry, that is not possible. You will have to either have a link to it in your README.md or copy its contents.
Github Flavored Markdown will show you what you can put in your README.md file.
Update : My answer works with github pages, built via jekyll. I use the script tags in markdown which is then processed by jekyll.
Since markdown supports html, one can simply use the <script> tag to embed gist.
Simply copy the embed url of the gist provided by github
..and paste it in you markdown file.
Example : Copy the below and paste in your markdown file.
<script src="https://gist.github.com/nisrulz/11c0d63428b108f10c83.js"></script>
..and this is what you will get
This is do-able in 2017 when using GitHub Pages and a Jekyll theme:
See https://gist.github.com/benbalter/5555251 from #benbalter
Simple as: {% gist 123456789 %}
You can do it if you are using a markdown preprocessor such as Gitdown:
/**
* Resolve Gist (https://gist.github.com/)
*
* #param {Object} config
* #param {String} config.id Gist ID.
* #param {String} config.fileName Gist file name. Default to gistfile1.txt.
*/
gitdown.registerHelper('gist', {
compile: function (config) {
config = config || {};
config.fileName = config.fileName || 'gistfile1.txt';
if (!config.id) {
throw new Error('Gist ID must be provided.');
}
return new Promise(function (resolve) {
var https = require('https');
https.get({
host: 'api.github.com',
path: '/gists/' + config.id,
headers: {
// User agent is required to communicate with Github API.
'user-agent': 'Gitdown – gist'
}
}, function(res) {
var body = '';
res.setEncoding('utf8');
res.on('data', function (d) {
body += d;
});
res.on('end', function () {
var gist = JSON.parse(body);
if (!gist.files) {
throw new Error('Gist ("' + config.id + '") not found.');
}
if (!gist.files[config.fileName]) {
throw new Error('File ("' + config.fileName + '") is not part of the gist ("' + config.id + '").');
}
resolve(gist.files['gistfile1.txt'].content);
});
});
});
}
});
Then in your markdown your would reference the Gist using a JSON hook, e.g.
{"gitdown": "gist", "id": "d3e4212c799252bac5fa"}
This feature should become part of the Gitdown in a near future (there is an open issue, https://github.com/gajus/gitdown/issues/7).
Some people will end up here due to the fact that they want to use auto-generated gists to make their profile on github more interesting with activity box, productive box, etc. (list of this stuff).
However, you should note that these auto-generated gists should not be added to your profile dedicated README file but should be pinned using the "Customize your pins" option on your profile page.