File saver is deprecated. How to resolve this issue from SonarQube - sonarqube

Working on filesaver, while running SONAR QUBE it shows " 'fileSaver' is deprecated. use { autoBom: false } as the third argument "
this.http.get(`getTemplate/${doc.id}`, { responseType: 'blob' }).subscribe(
(data: any) => {
fileSaver.saveAs(new Blob([data], { type: this.fileType }), doc.docName)
error :- 'fileSaver' is deprecated. use { autoBom: false } as the third argument
Even if I use autobom:false it still shows the same
Here is the code for autobom
this.http.get(`getDocument/${doc.docId}`, { responseType: 'blob' }).subscribe(
(data: any) => {
var blob = new Blob([data], { type: this.fileType });
fileSaver.saveAs(blob, doc.docName,false);
'saveAs' is deprecated. use { autoBom: false } as the third argumentWhy is this an issue?
'fileSaver' is deprecated. use { autoBom: false } as the third argument Why is this an issue?

It should be the setting of autoBom, not just false:
fileSaver.saveAs(blob, doc.docName, { autoBom: false });

I had the same issue. I fixed by importing only the function.
For ts
import { saveAs } from 'file-saver';
saveAs(blob, doc.docName);
For js
const { saveAs } = require('file-saver');
I think that this sonar issue is because the browsers do not natively support interface.

Related

RxJS subcribe is deprecated

I have trouble with subcribe method. In vscode it says that subcribe is deprecated but I have no clue how to change it properly.
public getAccount(): void{
this.accountService.getAccounts().subscribe(
(response: Account[]) => {
this.accounts = response;
},
(error: HttpErrorResponse) => {
alert(error.message);
}
)
}
You should pass an observer object instead of multiple callbacks. All signatures that used multiple arguments were deprecated.
this.accountService.getAccounts().subscribe({
next: (response: Account[]) => {
this.accounts = response;
},
error: (error: HttpErrorResponse) => {
alert(error.message);
},
complete: () => {
// do something when the observable completes
}
});
If you don't need an error and complete callbacks, you can still use it like this: .subscribe((value) => console.log(value)).
You can read about why the signature you're using was deprecated here.

How to stub a call to graphql using cypress?

I'm writing a Vue app that uses vue-apollo to interact with graphql. I'm wondering if it's possible to stub the graphql requests. I thought this should work:
it('should access a story', function() {
cy.server();
cy.route('http://localhost:3002/graphql', {
data: {
Story: { id: 2, title: 'story title', content: 'story content' }
}
});
cy.visit('/stories/2');
});
Unfortunately, I get an error from graphql complaining that id is an Int instead of an ObjectId. Am I missing something?
The problem was that stubbing fetch requests isn't yet implemented in Cypress (which is what Vue Apollo is using). I ended up following these instructions:
Install github/fetch
Add this to cypress/support/index.js:
.
Cypress.on('window:before:load', win => {
win.fetch = null;
win.Blob = null;
});
Now it works!
I got it working with this package here:
npm i #iam4x/cypress-graphql-mock
Add this line to 'support/commands.js'
import "#iam4x/cypress-graphql-mock";
go to your graphiql playground and download your schema
add task command to 'plugins/index.js' (REMEMBER TO CHANGE PATH TO SCHEMA FILE YOU DOWNLOADED EARLIER)
module.exports = (on, config) => {
on("task", {
getSchema() {
return fs.readFileSync(
path.resolve(__dirname, "../../../schema.graphql"),
"utf8"
);
}
});
};
write your tests with loaded schema
beforeEach(() => {
cy.server();
cy.task("getSchema").then(schema => {
cy.mockGraphql({
schema
});
});
});`
describe("Login Form", () => {
it("should redirect after login", () => {
cy.mockGraphqlOps({
operations: {
Login: {
login: {
jwt: "some-token",
user: {
id: "5d5a8e1e635a8b6694dd7cb0"
}
}
}
}
});
cy.visit("/login");
cy.getTestEl("email-input").type("Max Mustermann");
cy.getTestEl("password-input").type("passwort");
cy.getTestEl("submit").click();
cy.getTestEl("toolbar-title").should("exist");
});
})
Visit the original repo for further explanation as i find it less confusing. The package you have installed is just a working fork of this one:
https://github.com/tgriesser/cypress-graphql-mock

Can I use Loopback Model Validations only when a property is certain value

I have a "post"-model in strongloop loopback with some properties:
title
text
tags
category
published (true or false)
Is it possible to use the model validations in strongloop loopback, but only when I want to publish the post, not when I save it?
Set up a custom post.saveOrPublish() remote method that only calls post.isValid() when post.publish === true. Or use the built-in persistedModel.save() for everything without validation and use a custom post.publish() remote method for when you actually click the publish button, which would trigger your validation code before calling save().
saveOrPublish example: (not tested, just a rough idea):
module.exports = function(Post) {
Post.saveOrPublish = function(post, cb) {
if(post.publish) {
post.isValid(function(valid){
if(valid) {
Post.upsert(post, function(err, post) {
if(err) {cb(err, null);}
cb(null, post);
});
} else {
cb(new Error('Publishing requires a valid post.'), post)
}
});
} else {
Post.upsert(post, function(err, post) {
if(err) {cb(err, null);}
cb(null, post);
});
}
};
// don't forget the remote method def
Post.remoteMethod('saveOrPublish',
{
accepts: [{
arg: 'post',
type: 'object'
}],
returns: {
arg: 'result',
type: 'object'
},
http: {verb: 'post'}
}
);
};

Joi validation return only one error message

I have a three field form made of a name field, email field and a textarea. I'm using Joi 4.7.0 version along with hapijs. I use the object below validate the input. I receive the data object from an ajax call. When I fill all the three fields with wrong informations I get only the message relative to the first wrong field. Like that:
"{"statusCode":400,"error":"Bad Request","message":"name is not allowed to be empty","validation": {"source":"payload","keys":["data.name"]}}"
validate: {
payload: {
data: {
name: Joi.string().min(3).max(20).required(),
email: Joi.string().email().required(),
message: Joi.string().min(3).max(1000).required()
}
}
}
For explanation let suppose to not fill the three field. I get only one message error and not the message error of the others fields. Why?
It happens because Joi aborts early by default.
abortEarly - when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true.
*EDIT: Configuration has changed in hapi 8.0. You need to add abortEarly: false to the routes config:
var server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 8000,
routes: {
validate: {
options: {
abortEarly: false
}
}
}
});
*See the Joi API documentation for more details.
*Also, see validation under Hapi Route options.
So Joi stops the validation on the first error:
var Hapi = require('hapi');
var Joi = require('joi');
var server = new Hapi.Server('localhost', 8000);
server.route({
method: 'GET',
path: '/{first}/{second}',
config: {
validate: {
params: {
first: Joi.string().max(5),
second: Joi.string().max(5)
}
}
},
handler: function (request, reply) {
reply('example');
}
});
server.start();
server.inject('/invalid/invalid', function (res) {
console.log(res.result);
});
Outputs:
{ statusCode: 400,
error: 'Bad Request',
message: 'first length must be less than or equal to 5 characters long',
validation: { source: 'params', keys: [ 'first' ] } }
You can however configure Hapi to return all errors. For this, you need to set abortEarly to false. You can do this in server configuration:
var server = new Hapi.Server('localhost', 8000, { validation: { abortEarly: false } });
If you run the script now, you get:
{ statusCode: 400,
error: 'Bad Request',
message: 'first length must be less than or equal to 5 characters long. second length must be less than or equal to 5 characters long',
validation: { source: 'params', keys: [ 'first', 'second' ] } }
I'm not integrating with hapi.js, but I noticed that there is a ValidationOptions object which can be passed along. Inside that object is an abortEarly option, so this should work:
Joi.validate(request, schema, { abortEarly: false }
This can also be configured as follows:
Joi.object().options({ abortEarly: false }).keys({...});
Check out these type definitions for more ValidationOptions:
https://github.com/DefinitelyTyped/tsd/blob/master/typings/joi/joi.d.ts
The validation key no longer works with the Hapi.Server constructor in Hapi 8.0:
[1] validation is not allowed
I found the solution in a GitHub issue for hapi:
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({
host: HOST,
port: PORT,
routes: {
validate: {
options: {
abortEarly: false
}
}
}
});
// Route using Joi goes here.
server.route({});
server.start(function () {
console.log('Listening on %s', server.info.uri);
});
After some research, I found out it can be solved 2 ways:
[Segments.BODY]: Joi.object().keys({
value: Joi.string().required().error(new Error('Value is required and has to be a text!')),
})
or
[Segments.BODY]: Joi.object().keys({
password: Joi.string().required().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).min(8).label('Password').messages({
'string.pattern.base': 'Your {#label} does not matche the suggested pattern',
'string.base': `Your {#label} should match the suggested pattern`,
'string.empty': `Your {#label} can not be empty`,
'string.min': `Your {#label} has to be at least {#limit} chars`,
'any.required': `Your {#label} is required`,
}),
})

How to handle server side validation in Ember-Data 1.0.0

I'm using Ember 1.2.0 and the latest Ember Data Beta and wonder, how to handle server side errors (from API calls).
This question is quite similar, but it doesn't work.
At first, the becameInvalid method doesn't triggered. I'm using ember-validations (do I have to?)
My API sends an 422 status code and responses like that:
{"errors":{"name":["has already been taken"],"initial":["has already been taken"]}}
model.js
Docket.Customer = DS.Model.extend( Ember.Validations, {
name: DS.attr('string'),
initial: DS.attr('string'),
description: DS.attr('string'),
validations: {
name: {
presence: true
}
},
becameError: function() {
alert('there was an error!');
},
becameInvalid: function(errors) {
alert("Record was invalid because: " + errors);
}
});
controller.js
Docket.OrganizationCustomersController = Ember.ArrayController.extend({
actions: {
save: function () {
var customer = this.store.createRecord('customer');
customer.set('name', this.get('name'));
customer.set('initial', this.get('initial'));
customer.set('description', this.get('description'));
customer.save().then(function() {
console.log('jeah')
}, function() {
console.log('nooo')
});
}
}
});
The becameError method gets fired, but the becameInvalid method doesn't.
The second problem: even if the error is triggered, Ember.js adds the new record to the DOM. How can I prevent this behaviour?
Your errors json is ok, I think you are using the DS.RESTAdapter, and it doesn't implement the becameInvalid based in json with errors.
Just DS.ActiveModelAdapter have implemented in the moment, so I recommend you to change your adapter configuration to:
Docket.ApplicationAdapter = DS.ActiveModelAdapter;
In order to keep DS.RestAdapter, you can override its ajaxError method with the one from ActiveModelAdapter.
As for today the code, slightly adapted because some dependencies are needed, would be :
App.ApplicationAdapter = DS.RESTAdapter.extend({
// ... your own customizations,
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var response = Ember.$.parseJSON(jqXHR.responseText),
errors = {};
if (response.errors !== undefined) {
var jsonErrors = response.errors;
Ember.EnumerableUtils.forEach(Ember.keys(jsonErrors), function(key) {
errors[Ember.String.camelize(key)] = jsonErrors[key];
});
}
return new DS.InvalidError(errors);
} else {
return error;
}
}
});
Obviously you have a chance here to adapt to your backend specifics: HTTP code (422 is not a standard one) and format.
Source :
http://discuss.emberjs.com/t/how-to-handle-failure-to-save-on-server/3789

Resources