Custom extension VS code- persistence state - javascript

I am tyring to keep the information in the sidebar in my vscode extention that I bulit, but I am not sure how to do that:
main code in the extention.js file:
context.subscriptions.push(vscode.window.registerWebviewViewProvider(
'viewId',
sidebarProvider(context)
));
main code in sidebarProvider.js:
const {sidebar} = require('./sidebar');
const sidebarProvider = (context) => {
return {
resolveWebviewView: (webviewView) => {
sidebar(webviewView, context);
},
};
};
module.exports = sidebarProvider;
main code in sidebar.js:
const vscode = require('vscode');
// severity, confidence, line number
const {handleMessageFromWebview} = require('./extenfuncs')
const fs = require('fs');
const sidebarhtml = String(fs.readFileSync(String(__dirname + "/siedbarwebviewhtml.html")))
const sidebar = function (webviewView, context) {
webviewView.webview.onDidReceiveMessage(
(message) => {
handleMessageFromWebview(message, webviewView.webview)
}, undefined,
context.subscriptions)
const html = sidebarhtml
webviewView.webview.options = {
enableScripts: true,
};
webviewView.webview.html = html;
};
module.exports = {sidebar}
I tried to use getState and setState but it didn't work

Related

the json is override when i use fs.writefilesync

i wanted to add something to my son file but when I try to add it just override my son file can someone help me with this
const fs = require('fs')
const chalk = require('chalk')
const getNotes = function(){
return 'Your notes....'
}
// add note function
const addNote = function (title, body) {
const notes = loadNotes()
const duplicateNotes = notes.filter(function (note) {
return note.title === title
})
if (duplicateNotes.length === 0) {
notes.push({
title: title,
body: body
})
saveNotes(notes)
console.log(chalk.green.inverse('New note added!'))
} else {
console.log(chalk.red.inverse('Note title taken!'))
}
}
const saveNotes = function(notes){
const dataJSON = JSON.stringify(notes)
fs.writeFileSync('notes.json', dataJSON)
}
const loadNotes = function(){
try{
const dataBuffer = fs.readFileSync(notes.json)
const dataJSON = dataBuffer.toString();
return JSON.parse(dataJSON)
}catch (e){
return []
}
}
module.exports = {
getNotes: getNotes,
addNote: addNote,
}
when I run node app.js add --title="list" --body="apple" and then i add another different title and body it just override the --title="list" --body="apple why is that happening ?
It seems you just forgot the quotes:
const dataBuffer = fs.readFileSync(notes.json)
should be
const dataBuffer = fs.readFileSync('notes.json')

module.exports with function

I have several JavaScript files that I create enums. for example:
source.enum.js
const enumUtils = require('../enum.utils');
const EmailAddressesSourceType = enumUtils.createEnum([
['DIRECTORY', 'directory'],
['FILE', 'file'],
['ARRAY', 'array']
]);
module.exports = { EmailAddressesSourceType };
The enum.utils.js is just a file that do the simple function of creating an enum from array:
class EnumUtils {
constructor() { }
// This method takes a map of elements and converts them to freeze objects (an enum-like object).
createEnum(mapItems) {
if (!mapItems || mapItems.length <= 0) {
throw new Error(`No array received: ${mapItems} (1000000)`);
}
const mapList = new Map([...mapItems]);
const symbolMap = {};
mapList.forEach((value, key) => { symbolMap[key] = value; });
return Object.freeze(symbolMap);
}
}
const enumUtils = new EnumUtils();
module.exports = enumUtils;
Now since I have 5-6 js files with enums, I want to avoid 'const enumUtils = require('../enum.utils');' in each of them, and do it all together in index.js file, something like this:
const { EmailAddressStatus, EmailAddressType, SendEmailStepName } = require('./files/emailAddress.enum');
const { Placeholder } = require('./files/placeholder.enum');
const { EmailAddressesSourceType } = require('./files/sources.enum');
const { Mode, Status, Method } = require('./files/system.enum');
const { StatusIcon, Color, ColorCode } = require('./files/text.enum');
const createEnum = (mapItems) => {
if (!mapItems || mapItems.length <= 0) {
throw new Error(`No array received: ${mapItems} (1000000)`);
}
const mapList = new Map([...mapItems]);
const symbolMap = {};
mapList.forEach((value, key) => { symbolMap[key] = value; });
return Object.freeze(symbolMap);
};
module.exports = {
createEnum(Color), createEnum(ColorCode), createEnum(EmailAddressStatus), createEnum(EmailAddressType), createEnum(EmailAddressesSourceType),
createEnum(Method), createEnum(Mode), createEnum(Placeholder), createEnum(SendEmailStepName), createEnum(Status), createEnum(StatusIcon)
};
But, there are compilation error in:
module.exports = {
createEnum(Color), createEnum(ColorCode), createEnum(EmailAddressStatus), createEnum(EmailAddressType), createEnum(EmailAddressesSourceType),
createEnum(Method), createEnum(Mode), createEnum(Placeholder), createEnum(SendEmailStepName), createEnum(Status), createEnum(StatusIcon)
};
My question is, there is a workaround so enable me to reduce the 'const enumUtils = require('../enum.utils');' in each file of the enums js file?
Thanks!
UPDATE 1
The error I'm getting is this:
The current status of the file (before I was trying to refactor) - It works OK:
index.js
const { EmailAddressStatus, EmailAddressType, SendEmailStepName } = require('./files/emailAddress.enum');
const { Placeholder } = require('./files/placeholder.enum');
const { EmailAddressesSourceType } = require('./files/sources.enum');
const { Mode, Status, Method } = require('./files/system.enum');
const { StatusIcon, Color, ColorCode } = require('./files/text.enum');
module.exports = {
Color, ColorCode, EmailAddressStatus, EmailAddressType, EmailAddressesSourceType,
Method, Mode, Placeholder, SendEmailStepName, Status, StatusIcon
};
This guy, guy-incognito, solved for me the issue. Now it works like a charm. Thanks man!
const { EmailAddressStatus, EmailAddressType, SendEmailStepName } = require('./files/emailAddress.enum');
const { Placeholder } = require('./files/placeholder.enum');
const { EmailAddressesSourceType } = require('./files/sources.enum');
const { Mode, Status, Method } = require('./files/system.enum');
const { StatusIcon, Color, ColorCode } = require('./files/text.enum');
const createEnum = (mapItems) => {
if (!mapItems || mapItems.length <= 0) {
throw new Error(`No array received: ${mapItems} (1000000)`);
}
const mapList = new Map([...mapItems]);
const symbolMap = {};
mapList.forEach((value, key) => { symbolMap[key] = value; });
return Object.freeze(symbolMap);
};
module.exports = {
Color: createEnum(Color),
ColorCode: createEnum(ColorCode),
EmailAddressStatus: createEnum(EmailAddressStatus),
EmailAddressType: createEnum(EmailAddressType),
EmailAddressesSourceType: createEnum(EmailAddressesSourceType),
Method: createEnum(Method),
Mode: createEnum(Mode),
Placeholder: createEnum(Placeholder),
SendEmailStepName: createEnum(SendEmailStepName),
Status: createEnum(Status),
StatusIcon: createEnum(StatusIcon)
};

JavaScript: Jest doesn't recognise static functions

I'm following a tutorial which is using jest to test the javascript. The instructor created a static function called genesis() on a class called Block and it worked for him just fine, but when I tried to do it I got TypeError: block.genesis is not a function. If I remove the static keyword it recognises the function and the test passes.
Here is the class:
const { GENESIS_DATA } = require('./config');
class Block {
constructor({ timestamp, lastHash, hash, data }) {
this.timestamp = timestamp;
this.lastHash = lastHash;
this.hash = hash;
this.data = data;
}
static genesis() {
return new Block(GENESIS_DATA);
}
}
module.exports = Block;
And the test:
const Block = require('./block');
const { GENESIS_DATA } = require('./config');
describe('Block', () => {
const timestamp = 'a-date';
const lastHash = 'a-hash';
const hash = 'another-hash';
const data = ['blockchain', 'data'];
const block = new Block({ timestamp, lastHash, hash, data });
describe('genesis()', () => {
const genesisBlock = block.genesis();
it('returns a block instance', () => {
expect(genesisBlock instanceof Block).toBe(true);
});
it('returns the genesis data', () => {
expect(genesisBlock).toEqual(GENESIS_DATA);
});
});
});
The genesis method is part of the class, not the instance. You want to call Block.genesis() instead of block.genesis()

Trying to test if next function was called on router

i don't know if the questions is very clear, but probably looking at the code you'll understand.
i'm trying to see if the next() function was called on my router.
But everytime i use the debugger, i watch that the next i passed as a stub to my router don't get on my router as a stub, looks like it get lost on the way. If i extract the callback from the router and exports it separately, it works just fine. But i didn't want to separate things and export them.
const express = require('express');
const mostReadRouter = express.Router();
const mostReadBackEnd = require('../services/most-read-back-end');
const translateMostReadList = require('../services/most-read-service');
mostReadRouter.get('/', (req, res, next) => {
let mostReadUrl = req.query.most_read_url;
if (!mostReadUrl) {
logger.error('param most_read_url is required');
res.status(400).send('param most_read_url is required');
return;
}
let sendSucces = mostRead => {
logger.info(`sending most read list for url: ${mostReadUrl}`);
res.json(mostRead);
};
let sendError = error => {
if (isNotFoundError(error)) {
next();
} else {
next(error);
}
};
mostReadBackEnd
.getMostReadList(mostReadUrl)
.then(translateMostReadList, sendError)
.then(sendSucces, sendError)
.catch(sendError);
});
module.exports = mostReadRouter;
const chai = require('chai');
const {expect} = chai;
chai.use(require('sinon-chai'));
const sinon = require('sinon');
const sandbox = sinon.createSandbox();
const proxyQuire = require('proxyquire');
const statusStub = sandbox.stub();
const sendStub = sandbox.stub();
const getMostReadListStub = sandbox.stub();
const translateStub = sandbox.stub();
const jsonStub = sandbox.stub();
const thenStub = sandbox.stub();
process.env.CONFIGURATOR_API = 'xpto';
const router = proxyQuire('../../app/routes/most-read-router', {
'../services/most-read-back-end': {
getMostReadList: getMostReadListStub
},
'../services/most-read-service': {
translate: translateStub
}
});
describe('MostReadRouter', () => {
afterEach(() => sandbox.reset());
describe('#get(request,response,next)', () => {
it.only('should call next() when getMostReadList does not work` ', async () => {
getMostReadListStub.rejects(new Error('the error'));
let req = {
method: 'GET',
url: '/',
query: {
most_read_url: 'http://beatiful_url.com'
}
};
let res = {
json: jsonStub
};
let next = sandbox.stub();
await router(req, res, next);
expect(next).to.be.calledOnce;
});
})
});

Test plain javascript file returning different objects

Is it possible to test the code below with Jasmine testing tool or any other npm module like rewire or similar?
const AuthValidatorDumb = require('./src/AuthValidatorDumb');
const AuthValidator = require('./src/AuthValidator');
const config = require('../config');
let instance;
if (!instance) {
if (config.get('auth.enabled')) {
instance = AuthValidator;
} else {
instance = AuthValidatorDumb;
}
}
module.exports = instance;
I've got a variant for testing the code above.Suppose you have:
1) The code for index.js in the question above.
2) AuthValidator.js:
class AuthValidator {}
module.exports = AuthValidator;
3) AuthValidatorDumb.js:
class AuthValidatorDumb {}
module.exports = AuthValidatorDumb;
Here is test/index.spec.js:
const proxyquire = require('proxyquire');
const AuthValidator = require('../src/AuthValidator');
const AuthValidatorDumb = require('../src/AuthValidatorDumb');
describe('auth index', () => {
it('should return AuthValidator', () => {
const configMock = { get: () => 'sth' };
const Instance = proxyquire('../index', {
'../config': configMock,
});
expect(new Instance() instanceof AuthValidator).toBeTruthy();
});
it('should return AuthValidatorDumb', () => {
const configMock = { get: () => undefined };
const Instance = proxyquire('../index', {
'../config': configMock,
});
expect(new Instance() instanceof AuthValidatorDumb).toBeTruthy();
});
});

Categories