eslint indent rule indents decorated members - eslintrc

In order to enable indents for chained methods:
await PostModel
.findOne({
author: user.user,
_id: id,
})
.populate('tickets', 'title status');
I have added the following MemberExpression to my eslintrc, as per eslint docs
indent": ["error", "tab", { "MemberExpression": 1 }],
but now I am experiencing problem with decorators, which get indented although my preference is to have them aligned with the member.
#prop({ type: String, required: true })
password: string;
Is there a way to address those two cases without a conflict?

I got the same problem as you did, and found this comment help, give it a try?
{
rules: {
// ...
"indent": ["error", 2, { "ignoredNodes": ["PropertyDefinition"] }]
}
}

According to this issue, you can partially disable the indent rule for decorators:
indent: [
'error',
'tab',
{
MemberExpression: 1,
ignoredNodes: [
'FunctionExpression > .params[decorators.length > 0]',
'FunctionExpression > .params > :matches(Decorator, :not(:first-child))',
'ClassBody.body > PropertyDefinition[decorators.length > 0] > .key',
],
},
],
This works for me.

#bujhmt's answer actually solved my problem, however, I needed to make some changes to it.
Before:
export abstract class MyAbstractClass extends AnotherClass {
#Column()
name!: string;
^^^^--> Expected indentation of 8 spaces, found 4
#Column()
address!: string;
^^^^--> Expected indentation of 8 spaces, found 4
}
Then I changed my .eslintrc rule to this:
"indent": [
`error`,
4,
{
"ignoredNodes": [
`FunctionExpression > .params[decorators.length > 0]`,
`FunctionExpression > .params > :matches(Decorator, :not(:first-child))`,
`ClassBody.body > PropertyDefinition[decorators.length > 0] > .key`,
],
},
],
And the errors were gone.

Related

Can't change the pagination 'next' and 'prev' labels to my language in grid.js

There is no such option as change the prev and next button label in the documentation, and when i try to use string replacement or change the button innerHTML via Javascript, it doesn't work, is there any way that I can safely change the label?
You can use the language config (added since v1.5.0) to customize this:
new Grid({
columns: ['Name', 'Email', 'Title'],
sort: true,
search: true,
pagination: {
limit: 5
},
data: Array(50).fill().map(x => [
faker.name.findName(),
faker.internet.email(),
faker.name.title(),
]),
language: {
'search': {
'placeholder': '🔍 Search...'
},
'pagination': {
'previous': '⬅️',
'next': '➡️',
'showing': '😃 Displaying'
}
}
});
Also see this example: https://gridjs.io/docs/examples/i18n/

facetFilters in autocomplete algolia

I m facing difficulties setting facetFilters for algolia-autocomplete. If i want to filter based on a few organizations like :
source: $.fn.autocomplete.sources.hits(index, { hitsPerPage: 5, facetFilters:[ ['organization_id:1', 'organization_id:10'], ['listing_status:Published' ]] })
It works perfectly fine.
Now I want to pick the values from a text box, it does not work. If the value of a text box is
<input type="hidden" id="marketplace_organization_ids" value="'organization_id:1', 'organization_id:10'">
source: $.fn.autocomplete.sources.hits(index, { hitsPerPage: 5, facetFilters:[ [$('#marketplace_organization_ids').val()], ['listing_status:Published' ]] }),
Tried using array also but no result:
var name = ["'organization_id:1'","'organization_id:10'"];
source: $.fn.autocomplete.sources.hits(index, { hitsPerPage: 5, facetFilters:[ [name.join(',')], ['listing_status:Published' ]] })
I have used the above with one organization like and t works fine:
source: $.fn.autocomplete.sources.hits(index, { hitsPerPage: 5, facetFilters:[ ['organization_id:'+$('#user_organization_id').val() , 'distributors.id:'+$('#user_organization_id').val()] ] }),
Appreciate any help.
It seems that you are passing an incorrect value in your facetFilters, due to not parsing the value extracted from your input.
source: $.fn.autocomplete.sources.hits(index, {
hitsPerPage: 5,
facetFilters:[
[$('#marketplace_organization_ids').val()],
['listing_status:Published']
]
})
evaluates to
source: $.fn.autocomplete.sources.hits(index, {
hitsPerPage: 5,
facetFilters:[
["'organization_id:1', 'organization_id:10'"],
['listing_status:Published']
]
})
According to the Algolia's documentation about facetFilters, you should instead provide an array of strings rather a string representation of an array, e.g.
source: $.fn.autocomplete.sources.hits(index, {
hitsPerPage: 5,
facetFilters:[
['organization_id:1', 'organization_id:10'], // no more double-quotes
['listing_status:Published']
]
})
You can do that by splitting your value before passing it to the array:
const organizationFilter = $('#marketplace_organization_ids').val()
.split(',') // split string into array
.map(filter => filter.trim()) // remove whitespaces
console.log(organizationFilter); // ['organization_id:1', 'organization_id:10']

Joi when sibling then add extra rules at root

I have a complex validation which changes depending on the a value in the JSON.
{ type: 'a', thing: 1, foo: 'abc' }
{ type: 'b', thing: 2, bar: 123 }
I want to validate that if the type is a, then use one set of siblings, if b then use another set of siblings
I would like to use the when switch, but cant work out how to do this at the root.
Joi.object({
type: Joi.string().valid('a','b').required(),
thing: Joi.number().required()
}).when('type', {
switch: [
{ is: 'a', then: Joi.object({ foo: Joi.string() }) },
{ is: 'b', then: Joi.object({ bar: Joi.number() }) },
],
otherwise: Joi.forbidden(),
});
However this gives the following error:
Error: Invalid reference exceeds the schema root: ref:type
This kinda makes sense as an error but I don't know how to restructure this to get it to apply the selector at the root.
Im using latest JOI (16.0.1)
This can be resolved by prefixing the key name passed to .when() with a ., to denote the key as being relative to the object being validated:
Joi.object({
type: Joi.string().valid('a','b').required(),
thing: Joi.number().required()
})
.when('.type', { /* <-- prefix with . */
switch : [
{ is: 'a', then: Joi.object({ foo: Joi.string() }) },
{ is: 'b', then: Joi.object({ bar: Joi.number() }) },]
})
Here's a working example - hope that helps :-)

codemirror inner mode auto indentation problems

I'm having some trouble getting codemirror to apply the correct autoindentation to inner modes in a mixed mode.
You can see a live version of the mode (and how it's not working) here:
https://extremely-alpha.iodide.io/notebooks/216/ but in short the idea is to be able to use matlab style block delimiters to switch between languages like this:
%% js
[1,2,3].forEach(i => {
console.log(i)
})
%% py
for i in range(5):
for j in range(10):
print i+j
%% css
div#foo {
border: 1px solid pink
}
As you can see from my example link, the syntax highlighting works ok, but you'll also notice that the indentation is not working as desired.
The code for this codemirror mode is here on github. It is very much based on codemirror's html mixed mode.
I tried adding copyState to my code, again following the html mixed mode --
copyState: state => {
let local;
if (state.localState) {
console.log("state.localState copied");
local = CodeMirror.copyState(state.localMode, state.localState);
}
return {
token: state.token,
localMode: state.localMode,
localState: local
};
},
-- but this results in a different kind of weird indentation behavior, and doesn't end up working.
I've been banging my head against this for quite some time, and I haven't been able to piece it together via google, api docs and forums, so any help would be greatly appreciated! Thank you!
in case anyone comes across this problem in the future: it turns out codemirror modes do not typically come with sensible defaults built in, or at least they are not loaded by default when you use CodeMirror.getMode(...). In my case, I had to change from
const innerModes = {
js: CodeMirror.getMode({}, { name: "javascript" }),
py: CodeMirror.getMode({}, { name: "python" }),
md: CodeMirror.getMode({}, { name: "markdown" }),
css: CodeMirror.getMode({}, { name: "css" }),
raw: CodeMirror.getMode({}, { name: "text/plain" }),
fetch: CodeMirror.getMode({}, { name: "fetch" })
};
to:
const innerModes = {
js: CodeMirror.getMode(
{ indentUnit: 2, statementIndent: 2 },
{ name: "javascript" }
),
py: CodeMirror.getMode(
{ indentUnit: 4, hangingIndent: 4 },
{ name: "python" }
),
md: CodeMirror.getMode({}, { name: "markdown" }),
css: CodeMirror.getMode({ indentUnit: 2 }, { name: "css" }),
raw: CodeMirror.getMode({}, { name: "text/plain" }),
fetch: CodeMirror.getMode({}, { name: "fetch" })
};
This prevented NaNs from getting passed out of the indent function of the sub-modes.

MongoDB - "The dollar ($) prefixed field \'$$hashKey\' in \'fieldName".$$hashKey\' is not valid for storage.'"

While trying to update a document I'm getting the above error for the field timesToDisplay.
MongoDB version 2.6.7.
The whole model:
msg = {
'name': '',
'template': '',
'displayDurInMilliSec': 0,
'timesToDisplay': [],
'images': [],
'texts': [],
'screen': []
}
I guess I will be getting the same error with the other 3 array fields.
I've tried using $set but sill getting the same error.
The code:
function updateMessage(msg) {
var conditions = {_id: msg._id}
, update = { 'name': msg.name,
'template': msg.template,
'displayDurInMilliSec': msg.displayDurInMilliSec,
'timesToDisplay': msg.timesToDisplay,
'images': msg.images,
'texts': msg.texts,
'screen': msg.screen
}
messageModel.update(conditions, update, callback);
function callback(err, numAffected) {
if (!err) console.log(numAffected)
else console.log(err)
}
}
EDIT: The msg parameter is a document in itself:
{ _id: '557d58abd54955480db6694f',
name: 'msg99',
timesToDisplay: [ { startDate: '2015-06-19T21:00:00.000Z',
'$$hashKey': 'object:214',
endDate: '2015-06-25T21:00:00.000Z',
daysOfTheWeek: [Object],
startTimeOfDay: '11',
endTimeOfDay: '13' } ],
images: [],
texts: [],
screen: [ 1 ],
'$$hashKey': 'object:54',
displayDurInMilliSec: '40189',
template: 'templates/Template2.html' }
The $$hashkey field is added by AngularJS when working with ngRepeat or ngOptions. In the case of ngRepeat you can change the repeat string by appending track by $index to it. For using ngOptions you'll have to filter out that field yourself. AngularJS provides a quick solution for filtering it out: angular.toJson. This will filter out all fields prefixed with two dollar signs. Check out the documentation.
I realize that this isn't a MongoDB answer, but this specific error ($$hashkey), is usually due to AngularJS.