How to change the field delete instead of id in loopback? - mysql

I want to the delete a few rows in MySQL table using loopabck. But I don't want to use the id to delete the record. I'm trying it in Angular SDK. My code is:
ModelName.destroyById({ fieldName : myValue })
.$promise
.then(function() {
});
I'd be very thankful for ideas.

Seems like you need to use the destroyAll method, which does what you want, but you need to set up remoting for it first, since it's disabled by default:
ModelName.remoteMethod('destroyAll', {
isStatic: true,
description: 'Delete all matching records',
accessType: 'WRITE',
accepts: {arg: 'where', type: 'object', description: 'filter.where object'},
http: {verb: 'del', path: '/'}
});
Then after that you regenerate your Angular client and you can use it like this in the client side:
ModelName.destroyAll({ filter: { fieldName : myValue }}).$promise.then(...)
Note that using destroyAll is risky as if you have any mistakes in your code you will end up losing data. Enabling it to client side might be security concern.
Another way to do this is to write your own remote method which uses destroyAll in turn with proper validation of the inputs.

Related

Hooks not triggering when inserting raw queries via sequelize.query()

I have the following Employee model for a MySQL database:
var bcrypt = require('bcrypt');
module.exports = (sequelize, DataTypes) => {
const Employee = sequelize.define(
"Employee",
{
username: DataTypes.STRING,
password: DataTypes.STRING,
}, {}
);
return Employee;
};
Seeding the database is done by reading a .sql file containing 10,000+ employees via raw queries:
sequelize.query(mySeedingSqlFileHere);
The problem is that the passwords in the SQL file are plain text and I'd like to use bcrypt to hash them before inserting into the database. I've never done bulk inserts before so I was looking into Sequelize docs for adding a hook to the Employee model, like so:
hooks: {
beforeBulkCreate: (employees, options) => {
for (employee in employees) {
if (employee.password) {
employee.password = await bcrypt.hash(employee.password, 10);
}
}
}
}
This isn't working as I'm still getting the plain text values after reseeding - should I be looking into another way? I was looking into sequelize capitalize name before saving in database - instance hook
Your hooks won't be called until you use model's function for DB operation , so if you are running raw query , hooks will never be fired,
Reason : You can write anything inside your raw query , select/insert/update/delete anything , how does sequelize.js know that
it has to fire the hooks. This is only possible when you use methods
like
Model.create();
Model.bulkCreate();
Model.update();
Model.destroy;
And as per DOC raw query doesn't have hooks option to add.
And for MODEL queries you can check that it has option to
enable/disable hook.

How do you insert / find rows related by foreign keys from different tables using Sequelize?

I think I've done enough research on this subject and I've only got a headache.
Here is what I have done and understood: I have restructured my MySQL database so that I will keep my user's data in different tables, I am using foreign keys. Until now I only concluded that foreign keys are only used for consistency and control and they do not automatize or do anything else (for example, to insert data about the same user in two tables I need to use two separate insert statements and the foreign key will not help to make this different or automatic in some way).
Fine. Here is what I want to do: I want to use Sequelize to insert, update and retrieve data altogether from all the related tables at once and I have absolutely no idea on how to do that. For example, if a user registers, I want to be able to insert the data in the table "A" containing some user information and in the same task insert in the table B some other data (like the user's settings in the dedicated table or whatever). Same with retrievals, I want to be able to get an object (or array) with all the related data from different tables fitting in the criteria I want to find by.
Sequelize documentation covers the things in a way that every thing depends on the previous one, and Sequelize is pretty bloated with a lot of stuff I do not need. I do not want to use .sync(). I do not want to use migrations. I have the structure of my database created already and I want Sequelize to attach to it.
Is it possible insert and retrieve several rows related at the same time and getting / using a single Sequelize command / object? How?
Again, by "related data" I mean data "linked" by sharing the same foreign key.
Is it possible insert and retrieve several rows related at the same
time and getting / using a single Sequelize command / object? How?
Yes. What you need is eager loading.
Look at the following example
const User = sequelize.define('user', {
username: Sequelize.STRING,
});
const Address = sequelize.define('add', {
address: Sequelize.STRING,
});
const Designation = sequelize.define('designation', {
designation: Sequelize.STRING,
});
User.hasOne(Address);
User.hasMany(Designation);
sequelize.sync({ force: true })
.then(() => User.create({
username: 'test123',
add: {
address: 'this is dummy address'
},
designations: [
{ designation: 'designation1' },
{ designation: 'designation2' },
],
}, { include: [Address, Designation] }))
.then(user => {
User.findAll({
include: [Address, Designation],
}).then((result) => {
console.log(result);
});
});
In console.log, you will get all the data with all its associated models that you want to include in the query

How can I insert into MySQL Using ReactJS without passing parameters to PHP page

I have my data are rendered with DOM using ReactJS, i can create dynamic object within the same page as:
return (
React.createElement('form', {onSubmit: this.onSubmit, className: 'ContactForm', noValidate: true},
React.createElement('input', {
type: 'text',
className: errors.name && 'ContactForm-error',
placeholder: 'First Name (required)',
value: this.props.value.name,
onChange: this.onNameChange,
}),
React.createElement('input', {
type: 'email',
className: errors.email && 'ContactForm-error',
placeholder: 'Email (required)',
value: this.props.value.email,
onChange: this.onEmailChange,
}),
My query about how can I insert the data into DB like SQLLight without php in between
You cannot.
Both DBs you have mentioned are purely server side. Therefore you have to somehow pass data to the server and there using technology of your choice (php, nodejs, java, .net, ...) save it to the DB.
If you do want to have DB on client side (in browser) the closest thing you are going to get is wrapper like pouchDB or direct usage of underlying technologies like indexed database, web sql, maybe web storage

A Sequelize column that cannot be updated

Is it possible to create a column on a MySQL table using Sequelize that can be initialized when creating a new row, but never updated?
For example, a REST service allows a user to update his profile. He can change any field except his id. I can strip the id from the request on the API route, but that's a little redundant because there are a number of different models that behave similarly. Ideally, I'd like to be able to define a constraint in Sequelize that prevents the id column from being set to anything other than DEFAULT.
Currently, I'm using a setterMethod for the id to manually throw a ValidationError, but this seems hackish, so I was wondering if there's a cleaner way of doing this. Even worse is that this implementation still allows the id to be set when creating a new record, but I don't know a way around this as when Sequelize generates the query it calls setterMethods.id to set the value to DEFAULT.
return sequelize.define('Foo',
{
title: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
notEmpty: true
}
}
},
{
setterMethods: {
id: function (value) {
if (!this.isNewRecord) {
throw new sequelize.ValidationError(null, [
new sequelize.ValidationErrorItem('readonly', 'id may not be set', 'id', value)
]);
}
}
}
}
);
Look at this Sequelize plugin:
https://www.npmjs.com/package/sequelize-noupdate-attributes
It adds support for no update and read-only attributes in Sequelize models.
In your specific case, you could configure the attribute with the following flags:
{
title: {
type: DataTypes.STRING,
allowNull: false,
unique : true,
noUpdate : true
}
}
That will allow the initial set of the title attribute if is null, and then prevent any further modifications once is already set.
Disclaimer: I'm the plugin author.

Update user with Admin SDK

I am trying to update some user data via the admin SDK. I thought this would work
function directoryUpdate(userId, userDept, userLocation, userPhone, userTitle) {
var update = {
organizations:
{
name: "Next Step Living",
title: userTitle,
primary: true,
type: "work",
department: userDept,
location: userLocation
},
phones:
{
value: userPhone,
type: "work",
primary: true,
}
};
update = AdminDirectory.Users.update(update, userId);
Logger.log('User %s updated with result %s.', userId, update)
return true;
}
but it is not updating the organization or phone data on the record. It also does not throw any kind of error.
three questions, what is the proper syntax to do this update, I assume this works like the API update and behaves like an upsert, is that true, and what is the best practice for capturing any errors during the update. I would like to return a false when the update fails and capture that info. Thanks in advance for your help.
Thanks for your question!
This "inspired" me to work out how the update API worked, as I had got as far as retrieving a User object, updating the properties but had not worked out how to persist the data back to Google.
So, here's my prototype code, which appears to work (the objective being to reset the user's password based on entries in a spreadsheet).
It doesn't seem the most elegant code to me, being that there are two round-trips to the Admin API, and we have to post the email address twice, but I guess that is a side-effect of the JSON API.
var emailAddress = userListSheet.getRange(row, 1).getValue();
var password = userListSheet.getRange(row, 2).getValue();
Logger.log('Email: %s, Password: %s', emailAddress, password);
// Reset user's password
var user = AdminDirectory.Users.get(emailAddress);
user.password = password;
if (changePasswordAtNextLogin == 'Yes') {
user.changePasswordAtNextLogin = true;
}
AdminDirectory.Users.update(user, emailAddress);
Figured out the syntax issue. You do need a set of [] around the name value pairs under organization and phones. organizations:[{....}], phones:[{...}]}; and no, at the end of primary: true under phones. Also changed it from an update to a patch but not sure if that was really required;
update = AdminDirectory.Users.patch(update, userId);
And Yes, it did behave like an upsert and modified existing data and added new data just like the API.
Still need to figure out the best way to capture any errors though so if you have any suggestions please post them.
Looks like supplying an invalid email address is a fatal error that can not be caught and dealt with in code. What I did was get all the primary emails out of Google, store them in an array, and validate that the email I was using was in that list prior to running the update. Since everything else is just a string or logical replacement it should not throw any errors so I am confident that the script will not fail. Now all I have to worry about is the time limit.