In my app, for one basic model i get data so:
var baseAccounts = Restangular.all('accounts');
baseAccounts.getList().then(function(accounts) {
$scope.allAccounts = accounts;
});
var newAccount = {name: "Gonto's account"};
and then i send post request:
baseAccounts.post(newAccount);
But in my app also i have such route:
/accounts/batchimport
how can i send my newAccount object to model-url: accounts/batchimport?
is it possible?
and how?
Restangular has a set of custom methods.
which could be used to make a custom requests, like:
var baseAccounts = Restangular.all('accounts');
baseAccounts.getList().then(function(accounts) {
$scope.allAccounts = accounts;
});
var newAccount = {name: "Gonto's account"};
baseAccounts.customPost(newAccount, "batchimport"); // it will call the accounts/batchimport
Hope it will help.
Related
im trying to export a var to another file in a nodejs application, i ve managed to export it, but the result of the variable should change when a user logs in, does the export notice the change and export it again? If not how can i do it?
File im trying to export from, the arrow line is the var itself
var express = require('express');
var router = express.Router();
var url = require('url');
var userinfo ="aaa";
// User Api
router.get('/user/:userid', check_token, (req, res) => {
var userid = req.params.userid;
users.getById(userid)
.then(data => {
console.log(data)
userinfo=data; <--------------------------------------------------------------------
res.jsonp(data);
})
.catch(err => {
res.status(500).jsonp(err);
});
})
var routeinfo;
module.exports= {routeinfo : router,
userinfo: userinfo}
file im tryng to export to
var use_test=require('../routes/api')
var userf = require('../routes/api').userinfo;
var socket_io = require('socket.io');
var io = socket_io();
var socketio = {};
socketio.io = io;
var users = [];
io.on('connection', function(socket){
console.log('A user connected');
console.log(`Socket connected ${socket.id}`)
console.log(`User -> ${userf}`)
});
module.exports = socketio;
The way you are doing this is pretty unconventional to say the least.
The correct way making a middleware and use it for the userinfo, which is the standard way.
Some problems with this approach is, Your socket.io is dependant upon the user(or any auto ajax call) hitting the user/:userid route so for multiple user hitting the route, the userinfo will not be contained for that particular session. One user's userinfo will be shown for another user.
Think it in terms of session, a simplistic way would be using an object to hold the value in userid: userInfo format.
For the original problem, I think as you are using var userinfo ="aaa"; a string, it is not changing the pointer.
Maybe, using a object you can use the data as it will be pointers.
const userinfo = {
data: null
}
and then,
userinfo.data = data;
But I won't go into the details as this is not a good way to achieve what you are trying to achieve.
I am trying to understand the following code taken from a service created in a feathersjs app.
// Initializes the `users` service on path `/users`
const createService = require('feathers-knex');
const createModel = require('../../models/users.model');
const hooks = require('./users.hooks');
const filters = require('./users.filters');
module.exports = function () {
const app = this;
const Model = createModel(app);
const paginate = app.get('paginate');
const options = {
name: 'users',
Model,
paginate
};
// Initialize our service with any options it requires
app.use('/users', createService(options));
// Get our initialized service so that we can register hooks and filters
const service = app.service('users');
service.hooks(hooks);
if (service.filter) {
service.filter(filters);
}
};
This file is then imported as follows:
// many requires..
const feathers = require('feathers');
// more requires
const services = require('./services');
// other requires
const app = feathers();
Can someone explain as to what does the line
const app = this
do in the code that is creating the service?
It assigns the value of this to a variable (well, a constant) with a name that more clearly describes the value than this does. It is designed to make the code easier for maintainers to understand.
i want to access a model name userRegistration in my custom js file but every time its showing undefined and shows this error
TypeError: Cannot call method 'findOne' of undefined
please Check code
var loopback = require('loopback');
var app = loopback();
var nodemailer = require("nodemailer");
var smtpTransport = require("nodemailer-smtp-transport");
var path=require('path');
var fs=require('fs');
var Handlebars = require('handlebars');
exports.mailToUser=function(req,res,next){
var userNotification = app.models.UserNotification;
var userregister = app.models.UserRegistration;
userregister.findOne({where:{email:email}},function(err,userobj){
if(err){
next()
}
})
}
Thanks
You shouldn't use var app = loopback();
If you want to access to app you can require your server.js or some other ways existed. The simple one is requiring server
I'm trying to learn Socket.io and I'm a beginner in NodeJS.
I'm using JSON object as a kind of key-value store for mapping callback function with relevant event names. May be there is some other alternative to do it efficiently which I don't know. The problem is in the code below, when I call bob.printName() it prints the JSON object perfectly. But when I call the same function using the callbacks['connection'](), it says the JSON object is undefined. I would like to know the reason of that and also love to know any other efficient alternatives like PHP like array indexing.
/***
** index.js
***/
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var User = require('./User');
var bob = new User();
var callbacks = {
'connection': bob.printName
};
io.on('connection', function(socket){
bob.printName();
callbacks['connection']();
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
/***
** User.js
***/
var jsonObj = null;
function User() {
this.jsonObj = {
type: 'type',
body: 'body'
};
}
User.prototype.printName = function(){
console.log(this.jsonObj);
}
module.exports = User;
I'm currently trying to create a NodeJS server or something similar to mockup a REST API that reads in a JSON file and responds to requests with that data. I really only need GET requests supported. What is the best way to go about this?
Here's what I have so far:
/**
* Sample items REST API
*/
function ItemsRepository() {
this.items = [];
}
ItemsRepository.prototype.find = function (id) {
var item = this.items.filter(function(item) {
return item.itemId == id;
})[0];
if (null == item) {
throw new Error('item not found');
}
return item;
}
/**
* Retrieve all items
* items: array of items
*/
ItemsRepository.prototype.findAll = function () {
return this.items;
}
/**
* API
*/
var express = require('express');
var app = express();
var itemRepository = new ItemsRepository();
app.configure(function () {
// used to parse JSON object given in the body request
app.use(express.bodyParser());
});
/**
* HTTP GET /items
* items: the list of items in JSON format
*/
app.get('/items', function (request, response) {
response.json({items: itemRepository.findAll()});
});
/**
* HTTP GET /items/:id
* Param: :id is the unique identifier of the item you want to retrieve
* items: the item with the specified :id in a JSON format
* Error: 404 HTTP code if the item doesn't exists
*/
app.get('/items/:id', function (request, response) {
var itemId = request.params.id;
try {
response.json(itemRepository.find(itemId));
} catch (exception) {
response.send(404);
}
});
app.listen(8080); //to port on which the express server listen
I know that I would use the following to include the file, I just don't know how to stuff the data into Items.
var responseItemsData = require('./items-list.json');
This is trivial in node. You can load the data by requiring the .json file directly
var responseData = require('./my-json-file'); //.json extension optional
//Do this during your startup code, not during the request handler
Then to send it:
res.write(JSON.stringify(responseData));
The rest of the code you need is easily available in almost every node.js tutorial on the web.
You can use jasmine+sinon:
var Episode = Backbone.Model.extend({
url: function() {
return "/episode/" + this.id;
}
});
beforeEach(function() {
this.server = sinon.fakeServer.create();
});
afterEach(function() {
this.server.restore();
});
it("should fire the change event", function() {
var callback = sinon.spy();
this.server.respondWith("GET", "/episode/123",
[200, {"Content-Type": "application/json"},'{"id":123,"title":"Hollywood - Part 2"}']);
var episode = new Episode({id: 123});
// Bind to the change event on the model
episode.bind('change', callback);
// makes an ajax request to the server
episode.fetch();
// Fake server responds to the request
this.server.respond();
// Expect that the spy was called with the new model
expect(callback.called).toBeTruthy();
expect(callback.getCall(0).args[0].attributes)
.toEqual({id: 123,
title: "Hollywood - Part 2"});
});
more details in: https://github.com/cld-santos/simplologia/tree/master/javascript-lessons/src/test/javascript/Sinon
The easiest way is to simply use the static middleware.
var express = require('express');
var app = express();
app.use('/api', express.static(__dirname + '/data'));
app.use('.*', express.static(__dirname + '/assets'));
This assumes that you are eventually going to put the REST api at /api but that while you're testing your data is going to be in the data directory and that your CSS/JS/HTML is in the assets folder. In reality you can put it whereever you want, but you now can put all your dev json separate from your code.
I created a tool for this purpose
https://github.com/homerquan/kakuen