for some reason my put route is not working in sequelize - sql-update

this is my call
$.ajax({
url: "/api/user_data",
method: "PUT",
data: {
id: data.id,
level: newLevel,
point: addPoints
},
error: function(req, err) {
console.log(err)
}
}).then(result => {
console.log("user info updated");
console.log(result);
// window.location.replace("/members");
});
this is my route
app.put("/api/user_data", function(req, res) {
db.User.update(
{
points: req.body.points,
level: req.body.level,
},
{
where: {
id: req.body.id,
},
}
).then(function(result) {
res.json(result);
});
});
I am also getting an error saying "can't set headers after they are sent".
I had { force: true } set before and it was not working. When I set force: false the level would update but only after I logged out then logged back in. I'm not sure why that was happening at all but any help would be much appreciated.

Related

How to implement auth guard for graphql subscriptions (passportjs + cookies)

How I can pass user to the request?
Is there any possible way to implement something like SubscriptionAuthGuard?
without the subscription, everything works fine
Code:
GraphQLModule.forRoot({
installSubscriptionHandlers: true,
subscriptions: {
'subscriptions-transport-ws': {
onConnect: (connectionParams, webSocket) =>
new Promise((resolve) => {
passportInit(webSocket.upgradeReq, {} as any, () => {
resolve(webSocket.upgradeReq);
});
}),
},
},
context: ({ req }) => ({ req }),
}),
Error:
TypeError: Cannot set property 'authInfo' of undefined
This worked for me, I'm using JWT and bearer tokens.
GraphQL.module:
'subscriptions-transport-ws': {
path: '/graphql',
onConnect: (connectionParams) => {
return {
req: {
headers: { authorization: connectionParams.Authorization },
},
};
},
},
Guard:
#Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
async canActivate(context: ExecutionContext): Promise<boolean> {
try {
return (await super.canActivate(context)) as boolean;
} catch (e) {
throw new AuthenticationError(generalErrorMessages.invalidToken);
}
}
getRequest(context: ExecutionContext): Request {
const ctx = GqlExecutionContext.create(context);
return ctx.getContext().req;
}
}

Stubbing / Spy on global.fetch in Deno

I'm just getting into Deno, one of the things I'm a little unsure about is how to stub or create a spy for the global fetch function?
One solution is to simply wrap the fetch in a function which itself can by stubbed or spied on, but that seems like an unnecessary abstraction.
Any help would be much appreciated.
With denock you can mock the return object of the fetch call. Maybe not what you want but now you can test without a real call to the server.
https://deno.land/x/denock#0.2.0
import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
import { denock } from "https://deno.land/x/denock/mod.ts";
// function to test
async function fetchFromServer() {
const urlObject = new URL("https://jsonplaceholder.typicode.com/todos");
const response = await fetch(urlObject, {
method: "POST",
headers: new Headers({
"content-type": "application/json",
}),
body: JSON.stringify({
userId: 2,
id: 23024,
title: "delectus aut autem",
completed: false,
}),
});
return await response.json();
}
// mock return
denock({
method: "POST",
protocol: "https",
host: "jsonplaceholder.typicode.com",
headers: [
{
header: "content-type",
value: "application/json",
},
],
path: "/todos",
requestBody: {
userId: 2,
id: 23024,
title: "delectus aut autem",
completed: false,
},
replyStatus: 201,
responseBody: { example: "My mocked response" },
});
// test
Deno.test("fetch", async () => {
const actual = await fetchFromServer();
assertEquals({ example: "My mocked response" }, actual);
});

Issue in loopback's upsertWithWhere()

I'm using loopback3.x. Why upsertWithWhere function always updates the same instance? Only one instance is there for all the time when updateWithWhere function executes.
app.models.oneTimePassword.upsertWithWhere({
where: {
userId: user.id
}
}, {
userId: user.id,
otp: otp,
updatedAt: updatedAt,
type: 'email'
}, (err, res) => {
if (!err) {
callback(null, {
status: "OK",
message: "email sent"
});
} else {
callback(err);
}
});
app.models.oneTimePassword.upsertWithWhere(
{
userId: user.id
},
{
userId: user.id,
otp: otp,
updatedAt: updatedAt,
type: 'email'
},
(err, res) => {
if (!err) {
callback(null, {
status: "OK",
message: "email sent"
});
} else {
callback(err);
});
Try this, The first argument of upsertWithWhere should be where therefore, you don't need to add where: {} check out this official documentation

Ember.js dynamic routes not resolving in test, but work in production

So, I'm trying to use the Twitter-style URL syntax, allowing a user to go to example.com/quaunaut to visit the user page of the user with the username 'quaunaut'. I was able to accomplish this via:
app/router.js
export default Router.map(function() {
this.route('users.show', { path: '/:user_username' });
});
app/routes/users/show.js
export default Ember.Route.extend({
model: function(params) {
return this.store.find('user', { username: params.user_username }).then(function(result) {
return result.get('firstObject');
});
},
serialize: function(model) {
return { user_username: model.get('username') };
}
});
Now, when live or run via ember s, this works fantastically. However, in tests, it seems for some reason to not resolve.
var application, server, USERS;
USERS = {
'example1': [{
id: 1,
username: 'example1'
}],
'example2': [{
id: 2,
username: 'example2'
}]
};
module('Acceptance: UsersShow', {
beforeEach: function() {
application = startApp();
server = new Pretender(function() {
this.get('/api/users', function(request) {
return [
201,
{ 'content-type': 'application/javascript' },
JSON.stringify(USERS[request.queryParams.username])
];
});
});
},
afterEach: function() {
Ember.run(application, 'destroy');
server.shutdown();
}
});
test('visiting users.show route', function(assert) {
visit('/example1');
andThen(function() {
assert.equal(currentPath(), 'users.show');
assert.equal(find('#username').text(), 'example1');
});
});
Which results in the following test results:
Acceptance: UsersShow: visiting users.show route
✘ failed
expected users.show
✘ failed
expected example1
So, any ideas why currentPath() isn't resolving? If you also have any recommendations for better means to implement what I'm looking to do here, I'm certainly open to it.
Your visit syntax isn't quite right, should be:
test('visiting users.show route', function(assert) {
visit('/example1').then(function() {
assert.equal(currentPath(), 'users.show');
assert.equal(find('#username').text(), 'example1');
});
});

Push info to the store in a success after an ajax request in ember

I'm new with ember and I wanted to know if it was possible to push some information that I've got back from my server into the store in ember.
I've tried this :
$.ajax({
url: host,
type: 'POST',
data: data,
accepts: 'application/json',
success: function(data) {
login.reset();
console.log("DEBUG: Login Succeed");
model: function() {
this.store.push() {
id: data.session.user.id,
username: data.session.user.username
}
}
login.transitionTo('home');
},
error: function() {
login.reset();
login.set('loginFailed', true);
console.log("DEBUG: Login Failed");
}
});
But obviously I'm wrong, and I don't really know how to do it :/
thanks for your help !!
EDIT:
Here is the new working code. I just forgot a small thing... such as the name of the model..
$.ajax({
url: host,
type: 'POST',
data: data,
accepts: 'application/json',
success: function(data) {
login.reset();
console.log("DEBUG: Login Succeed");
login.store.push('user', {
id: data.session.user.id,
username: data.session.user.username,
firstname: data.session.user.firstname,
lastname: data.session.user.lastname,
email: data.session.user.email,
domainid: data.session.user.domain,
role: data.session.user.role,
status: data.session.user.status
});
login.transitionTo('home');
},
error: function() {
login.reset();
login.set('loginFailed', true);
console.log("DEBUG: Login Failed");
}
});