How do I get Sails.js to query an existing database? - sql-server

There's a dev database already set up for another project. I'm trying to create a sails.js server to connect to this database and act as a RESTful API. I'm also using SQL Workbench with the profile below to connect to the database and verify my query statements. On that tool, I'm able to send queries like select top 10 * from advisor and get the data I expect in response.
My connection configuration in sails.js seems to be alright, since I'm able to start the server. I've gotten simple static actions to work, like hi: function (req, res) { return res.send("Hi there!"); }. However, I can't figure out what to do to get a response from the database served by sails. My goal (at this point) is to have http://localhost:1337/advisor return JSON for the results of select top 10 * from advisor.
I initially tried using the freshly-generated model. Then, I tried adding attributes to the model file. Then, I tried adding my own code to the controller. In each case, the browser never received a response. At the end, I tested /advisor/list to run my own code and it doesn't look like the query() callback was ever executed. In case it's the first question, I have run npm install sails-sqlserver and I've double-checked that my host, db, username, & password are identical to what was used in Workbench.
connections.js
sqlserver: {
adapter: 'sails-sqlserver',
user: 'myusername',
password: 'mypassword',
host: 'mysubdomain.mydomain.net:1433',
database: 'frontofficedev'
}
models.js
module.exports.models = {
connection: 'sqlserver',
migrate: 'safe'
};
api\models\Advisor.js
module.exports = {
attributes: {
advcode: 'string',
advname: 'string',
'adv-default': 'boolean',
"user-id": 'string',
"pc-code": 'string',
"adv-tag": 'string',
"is-group": 'boolean',
"trade-grouping": 'string',
AdvisorId: 'int',
orgcode: 'string',
BranchId: 'int',
OrdPrnBranchId: 'int',
zdec1: 'float',
zdec2: 'float',
zchar1: 'string',
zchar2: 'string',
zchar3: 'string',
zchar4: 'string',
AdvStatus: 'string'
}
};
api\controllers
module.exports = {
hi: function (req, res) {
return res.send("Hi there!");
},
list: function (req, res) {
var myQuery = "select TOP 10 * from advisor";
sails.log.debug("Query :", myQuery);
console.log(Advisor);
Advisor.query(myQuery, function (err, advisors){
console.log(advisors);
console.log(err);
if(err || !advisors.rows.length){
return res.json({"status": 0, "error": err});
}
else{
return res.json(advisors);
}
});
}
};
Any ideas on what I'm doing wrong? Is JDBC causing problems? Thanks in advance.

Im assuming you've already run: npm install sails-sqlserver --save
You have to specify your connection and the table you will be using in the model, the variables in the model should match with your DB variables, like this:
api\models\Advisor.js
module.exports = {
schema: true,
connection: 'sqlserver',
tableName: 'yourTableName',
attributes: {
advcode:{
type: 'string',
primaryKey: true //if this is a primary key
},
advname:{
type: 'string'
},
'adv-default':{
type: 'boolean'
}
};
In your controller you can use the Sails ORM waterline like this:
api\controllers
module.exports = {
list: function (req, res) {
Advisor.query('SELECT * FROM advisor', function(err, results) {
if (err) {
res.send(400);
} else {
res.send(results);
}
});
}
};
Where Advisor is the model.
For more specific information about models and ORM waterline i recommend you read the sails docs: http://sailsjs.org/documentation/reference/waterline-orm/models

My colleague spotted the problem. The port that database lives on needs to be a separate attribute in sails' connection.js (instead of including it in the host string). No need for extra libraries, like node-jdbc.
config/connections.js
sqlserver: {
adapter: 'sails-sqlserver',
user: 'myusername',
password: 'mypassword',
host: 'mysubdomain.mydomain.net',
port: 1433,
database: 'frontofficedev'
}
After making that change, I was able to delete all my custom code from the controller and almost everything from the model (I still need to specify a primary key, since sails looks for id by default and the database was using AdvisorId.
api/models/Advisor.js
module.exports = {
attributes: {
AdvisorId: {primaryKey: true}
}
};

Related

Sequelize Op.like and Op.or failing

i have this issue with Sequelize:
I'm trying to have a 3 parameter research and if one of those parameter is empty it should not consider that parameter.
const users = await User.findAll({
where: {
category: { [Op.like]: `%${req.query.category}%` },
location: { [Op.like]: `%${req.query.location}%` },
[Op.or]: [
{ job: { [Op.like]: `%${req.query.job}%` } },
{ bio: { [Op.like]: `%${req.query.job}%` } },
{ skills: { [Op.like]: `%${req.query.job}%` } },
],
},
attributes: { exclude: ['password', 'createdAt', 'updatedAt'] },
})
I've found out that the [Op.like] is not working anywhere.
It only works if a parameter is empty (blocks that parameter from filtering the users and that's something i like).
When i do a research with the example payload {category:'Information Technology', job:'frontend web dev', location:'Sydn'} this is logged in the process log:
Executing (default): SELECT `id`, `email`, `firstName`, `lastName`, `image`, `location`, `phone`,
`website`, `availability`, `category`, `job`, `skills`, `bio` FROM `Users` AS `User`
WHERE (`User`.`job` LIKE '%frontend web dev%' OR `User`.`bio` LIKE '%frontend web dev%' OR
`User`.`skills` LIKE '%frontend web dev%') AND `User`.`category` LIKE '%Information Technology%'
AND `User`.`location` LIKE '%Sydn%';
but no user is found. (yes, in the database I have users with similar parameters)
In my opinion your code and your logged SQL are same. I don't see any errors. Maybe you should try to copy that SQL and paste it in MySQL Workbench (if you're using MySQL) then try to run it.
I think it should looks more like this:
category: { [Op.like]: '%`${req.query.category}%`' },
What I did here is add single quote mark '. Reference to the documentation

SequelizeDatabaseError Data truncated for column position at row 4

I am getting a SequelizeDatabaseError Data truncated for column 'position' at row 4 while sending an update request as below: Any advise on how to fix the database error ?
Executing (default): UPDATE user SET photo=?,name=?,email=?,phonenumber=?,position=?,password=?,updatedAt=? WHERE email = ?
SequelizeDatabaseError: Data truncated for column 'position' at row 4
at Query.formatError (C:\Project\soccerpep\node_modules\sequelize\lib\dialects\mysql\query.js:244:16)
at Execute.handler [as onResult] (C:\Project\soccerpep\node_modules\sequelize\lib\dialects\mysql\query.js:51:23)
module.exports = function(sequelize, DataTypes) {
return sequelize.define('user', {
name: {
type: DataTypes.STRING(30),
allowNull: false
},
email: {
type: DataTypes.STRING(100),
allowNull: false
},
phonenumber: {
type: DataTypes.STRING(50),
},
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
password: {
type: DataTypes.STRING(50),
allowNull: false
},
privilege: {
type: DataTypes.ENUM('PLAYER','ADMIN'),
},
photo: {
type: DataTypes.STRING(30),
},
position: {
type: DataTypes.ENUM('FORWARD','MID-FIELD','DEFENDER','GK'),
}
}, {
tableName: 'user'
});
};
server.js
const UserModel = userSchema(sequelize, DataTypes);
app.put('/service/profile', async (req, res, next) => {
try {
const userEmail = req.query.email;
var selector = {
where: { email: userEmail }
};
const updatePlayer = await UserModel.update(req.body, selector);
console.log("Server side update method log:" + updatePlayer);
res.status(200).json({ success: true });
} catch (err) {
return next(err);
}
});
I think the issue is with ENUM, you can use that only with Postgres and not with mysql , ( Ref )
position: {
type: DataTypes.ENUM('FORWARD','MID-FIELD','DEFENDER','GK'),
}
Change it to simple string type and check again,
position: {
type: DataTypes.STRING(30)
}
NOTE : You might need to create table again or update the field
manually after changing this in model else you will still get the
error
If you want to use ENUMs in mysql you should use it as so
position: {
type: DataTypes.ENUM,
values: ['player', 'admin],
defaultValue: 'monthly' // A default value just incase you fail to provide one...
},
I do hope this helps...
Change datatype is not the solution. You have to check the data that you try to save. eg: if ENUM("0", "1") and you try to saved data 0 then it's showing that type of error. You have to save like that "0". Then it's not showing such type of error message again.
i have a lot spending my day to tracing this error.
i have following all solution but doesnt work.
in my case and my bad is...
i forgot have clone table/duplicate/history/trigger that save old and new data.
make sure your history table have same data type.
i have table like these
form3
hs_form3 // its mean history with revision (number of revisi data) column and action column (create/update/delete/any)
just for description
CREATE TABLE hs_form3 LIKE form3;
ALTER TABLE hs_form3 MODIFY COLUMN id int(11) NOT NULL,
DROP PRIMARY KEY, ENGINE = InnoDB, ADD action VARCHAR(8) DEFAULT 'insert' FIRST,
ADD revision INT(6) NOT NULL AUTO_INCREMENT AFTER action,
ADD dt_datetime DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER revision,
ADD PRIMARY KEY (revision),
ADD KEY `user_id` (`user_id`),
and i didnt run migration on server because a lot of change , i only run on localhost. in server i just put a new table by export import or added manual. before i got issue about migration on server and doesnt capture last change in sql table and dont have time to resolve.

Creating a record with an n:m relationship, using Sequelize, NodeJS, and AngularJS

Update: I've gotten a fair bit further. Please see the bottom of the post...
I'm working on a project that is based on the sql-fullstack yeoman generator, and have been using the included example code as a guide. Things have progressed smoothly, for the most part, but I'm now in a scenario where I have two tables/models with a bidirectional n:m relationship:
TaskGroup:
module.exports = function(sequelize, DataTypes) {
var TaskGroup = sequelize.define("TaskGroup", {
taskGroupID: {
field: "TaskGroupID",
type: DataTypes.INTEGER,
allowNull: false,
unique: true,
autoIncrement: true,
primaryKey: true
},
name: {
field: "Name",
type: DataTypes.STRING,
allowNull: false
},
description: {
field: "Description",
type: DataTypes.STRING
},
modifiedBy: {
field: "ModifiedBy",
type: DataTypes.STRING
}
});
and Task:
module.exports = function(sequelize, DataTypes) {
var Task = sequelize.define("Task", {
taskID: {
field: "TaskID",
type: DataTypes.INTEGER,
allowNull: false,
unique: true,
autoIncrement: true,
primaryKey: true
},
name: {
field: "Name",
type: DataTypes.STRING,
allowNull: false
},
description: {
field: "Description",
type: DataTypes.STRING
},
isOnRunsheet: {
field: "IsOnRunsheet",
type: DataTypes.BOOLEAN
},
modifiedBy: {
field: "ModifiedBy",
type: DataTypes.STRING
}
});
Relationships:
// Tasks can belong to more than one group, and groups can belong to more than one task
db['TaskGroup'].belongsToMany(db['Task'], {as: 'Tasks', through: 'TaskGrouping'});
db['Task'].belongsToMany(db['TaskGroup'], {as: 'TaskGroups', through: 'TaskGrouping'});
On the client side, the user is able to create a new task and specify the associated task groups through a multiple select list. When the task is saved, I have both the task fields and an array of the associated task groups. A post is made with the request body containing this information, so that the server can create the task record.
Unfortunately, I can't seem to get the record created. I've been through a number of iterations, and I'm at the point where I get what appears to be a reasonable exception - I'm just stumped as to what the "reasonable" thing to do is...
Exception:
Unhandled rejection SequelizeDatabaseError: Cannot insert the value NULL into column 'TaskTaskID', table 'HelpCard
.dbo.TaskGrouping'; column does not allow nulls. INSERT fails.
at Query.formatError (C:\Projects\helpcard2\node_modules\sequelize\lib\dialects\mssql\query.js:215:10)
at Request.userCallback (C:\Projects\helpcard2\node_modules\sequelize\lib\dialects\mssql\query.js:66:25)
at Request.callback (C:\Projects\node_modules\tedious\lib\request.js:33:27)
at Connection.message (C:\Projects\node_modules\tedious\lib\connection.js:1179:27)
at Connection.dispatchEvent (C:\Projects\node_modules\tedious\lib\connection.js:519:45)
at MessageIO.<anonymous> (C:\Projects\node_modules\tedious\lib\connection.js:439:23)
at emitNone (events.js:67:13)
at MessageIO.emit (events.js:166:7)
at ReadablePacketStream.<anonymous> (C:\Projects\node_modules\tedious\lib\message-io.js:92:15)
at emitOne (events.js:77:13)
...
Here's the code on the client side:
$scope.createTask = function() {
if($scope.newTask === '') {
return;
}
$scope.newTask.modifiedBy = 'tkturney';
var taskBundle = {
task: $scope.newTask,
taskGroups: $scope.selectedGroups
};
$http.post('/api/tasks', taskBundle);
setTimeout(function() {
$scope.currentTask = $scope.newTask;
$scope.newTask = '';
$scope.addingTask = false;
refreshTasks();
}, 250);
};
...and on the server side:
exports.create = function(req, res) {
var task = Task(req).build(req.body.task);
task.setTaskGroups(req.body.taskGroups);
task
.save()
.then(function() {
return res.status(201).json(task);
})
.catch(function (err){
if(err) { return handleError(res, err); }
});
};
I'm sure that I'm missing something obvious, but the documentation that I've found has been pretty light on a scenario like this. I would appreciate any guidance; I'm just getting into sequelize, and I feel that there are times that I may have bitten off more than I can chew... :)
Update: After taking a closer look at the SQL, I discovered that the exception was being thrown when trying to insert into the join table (TaskGroupings). It was trying to insert a NULL for the task's primary ID, which is generally not a good thing. Looking at the code, I realized that I was trying to add the association before I had saved the record, leaving me with no PK. Moving the task.addTaskGroups() after the save() took care of that issue.
However, I also realized that I was passing an array of TaskGroup objects to the 'addTaskGroup()` call, instead of the actual IDs. So, I modified the client-side controller like so:
$scope.createTask = function() {
if($scope.newTask === '') {
return;
}
$scope.groupKeys = [];
angular.forEach($scope.selectedGroups, function(taskGroup) {
$scope.groupKeys.push(taskGroup.taskGroupID);
});
$scope.newTask.modifiedBy = 'tkturney';
var taskBundle = {
task: $scope.newTask,
taskGroups: $scope.groupKeys
};
$http.post('/api/tasks', taskBundle);
...
When I look at the debugger, I can see everything in the taskGroup object, but taskGroup.taskGroupID is coming back as undefined, so I'm still getting an exception because I'm not passing the PKs for the other side of the association.
Does anything leap out as to what might be screwy with this code fragment?
Ok, by changing the server-side controller from this:
exports.create = function(req, res) {
var task = Task(req).build(req.body.task);
task.setTaskGroups(req.body.taskGroups);
task
.save()
.then(function() {
return res.status(201).json(task);
})
.catch(function (err){
if(err) { return handleError(res, err); }
});
};
To this:
exports.create = function(req, res) {
var task = Task(req).build(req.body.task);
task
.save()
.then(function() {
task.setTaskGroups(req.body.taskGroups);
return res.status(201).json(task);
})
.catch(function (err){
if(err) { return handleError(res, err); }
});
};
That particular exception went away. The thing that I was missing (though it was staring me in the face) was the fact that there are two separate inserts happening - one for the task, and one for the association. I was thinking that I needed to set the association before saving the task, not realizing that setting that association caused another insert.
I still need to figure out why the PKs for the other side of the association aren't getting populated, but that's outside the scope of the original question...

How to connect to SQL Server with windows authentication from Node.JS using mssql module

Hi I'm unable to connect to SQL server that is using windows authentication in node js. I'm using the mssql module. The error message is :
[ConnectionError: Login failed for user ''. The user is not associated with a trusted SQL Server connection.]
name: 'ConnectionError',
message: 'Login failed for user \'\'. The user is not associated with a trusted SQL Server connection.',
code: 'ELOGIN' }
Here is my code:
config = {
server : "localhost\\MSSQLSERVER",
database : "mydatabase",
port : 1433
}
function loadDepts() {
var conn = new sql.Connection(config);
var request = sql.Request(conn);
conn.connect(function(err) {
if (err) {
console.log(err);
return;
}
request.query("select deptid, deptname from departments", function(err, table) {
if (err) {
console.log(err);
return;
}
else {
console.log(table);
}
conn.close();
});
});
}
loadDepts();
Since this is a fairly visible answer, I wanted to add in a code snippet that worked for me with Trusted Connection. Got to it from getglad's edited answer.
const sql = require("mssql");
require("msnodesqlv8");
const conn = new sql.Connection({
database: "db_name",
server: "server_name",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
conn.connect().then(() => {
// ... sproc call, error catching, etc
// example: https://github.com/patriksimek/node-mssql#request
});
Using trusted connection, I was able to execute stored procedures, log the output, and close the connection without any trouble, and msnodesqlv8 has been updated more recently than any of the other drivers (latest release was October 2016 as of 11/3/2016), so that seems to be a safe choice as well.
And here's an example using mssql#4.0.4. The only changes are the initial require, which pull in msnodesqlv8 from within mssql, and sql.Connection is now sql.ConnectionPool. You will also need to change your stored procedure calls since the response is different, noted here. Credit to Jon's answer since he updated mine before I did!
const sql = require("mssql/msnodesqlv8");
const conn = new sql.ConnectionPool({
database: "db_name",
server: "server_name",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
conn.connect().then(() => {
// ... sproc call, error catching, etc
// example: https://github.com/patriksimek/node-mssql#request
});
I have been struggling too for some time about how to use mssql + Windows Auth, here is how i got it to work on my project.
As pointed out in the mssql documentation, you need msnodesqlv8 installed too.
npm install msnodesqlv8
Now, following on Aaron Ballard's answer, you use it like this:
const sql = require('mssql/msnodesqlv8')
const pool = new sql.ConnectionPool({
database: 'database',
server: 'server',
driver: 'msnodesqlv8',
options: {
trustedConnection: true
}
})
pool.connect().then(() => {
//simple query
pool.request().query('select 1 as number', (err, result) => {
console.dir(result)
})
})
As a note, i tried to add this as a comment on Aaron's answer, as mine is just a complement/update to his, but i don't have enough reputation to do so.
I have never been able to get mssql + windows auth to work for any of my projects. Try edge and edge-sql - it has worked for me. Be sure you install all the required packages.
https://github.com/tjanczuk/edge
https://github.com/tjanczuk/edge-sql
From there, it's pretty steamlined.
var edge = require('edge');
var params = {
connectionString: "Server=YourServer;Database=YourDB;Integrated Security=True",
source: "SELECT TOP 20 * FROM SampleData"
};
var getData = edge.func( 'sql', params);
getData(null, function (error, result) {
if (error) { console.log(error); return; }
if (result) {
console.log(result);
}
else {
console.log("No results");
}
});
EDIT
Well... 10 days after my original answer, apparently mssql added Windows Auth to the package. They heard our cries :) See here. I have not tested it yet, but it is officially in my backlog to test integration. I will report back.
FWTW, if mssql fits your needs, I would go with it, as 1) edge-sql has been dormant for 2 years and 2) the primary contributor has said he has left projects like this "in the caring hands of Microsoft", since he no longer works there.
EDIT 2
This keeps getting upvotes and there are comments saying some of the other answers' code examples either aren't working or aren't working on Windows.
This is my code using mssql, working on Windows, with msnodesqlv8 also installed:
var sql = require('mssql/msnodesqlv8');
var config = {
driver: 'msnodesqlv8',
connectionString: 'Driver={SQL Server Native Client XX.0};Server={SERVER\\NAME};Database={dbName};Trusted_Connection={yes};',
};
sql.connect(config)
.then(function() {
...profit...
})
.catch(function(err) {
// ... connect error checks
});
I've tried many variations and this is my complete solution.
I'm using SQL server Express.
I'm connecting, in the first instance, to the MASTER database only.
You only NEED to change "YOURINSTANCE\\SQLEXPRESS".
(Be sure to maintain the double-slash above!!!)
I'm using INTEGRATED SECURITY too.
The query relies on nothing at all (in your database).
You need to add your node packages
==> NPM INSTALL MSSQL and
==> NPM INSTALL msnodesqlv8
Hopefully, your connection issues will be a thing of the past.
Maybe.
Please.
// More here -> https://www.npmjs.com/package/mssql
var sql = require('mssql/msnodesqlv8');
var config = {
connectionString: 'Driver=SQL Server;Server=YOURINSTANCE\\SQLEXPRESS;Database=master;Trusted_Connection=true;'
};
sql.connect(config, err => {
new sql.Request().query('SELECT 1 AS justAnumber', (err, result) => {
console.log(".:The Good Place:.");
if(err) { // SQL error, but connection OK.
console.log(" Shirtballs: "+ err);
} else { // All is rosey in your garden.
console.dir(result);
};
});
});
sql.on('error', err => { // Connection borked.
console.log(".:The Bad Place:.");
console.log(" Fork: "+ err);
});
For me
I used connection setting as below
"server":"",
"domain":"", //sepcify domain of your user
"port": ,
"user":"", // enter username without domain
"password":"",
"database":""
and the TS code
import * as sql from 'mssql';
const pool = await new sql.ConnectionPool(connection).connect();
const result = await pool.request()
.query(`SELECT count(idpart) part_computed FROM demo.PARTs;`);
pool.close();
return Promise.resolve(result.recordset);
I could only get a Trusted Connection working using msnodesqlv8 (limited to Windows environments) with a connection string (rather than a config object).
const sql = require("msnodesqlv8");
const connectionString = function(databaseName) {
return "Server=.;Database=" + databaseName + ";Trusted_Connection=Yes;Driver={SQL Server Native Client 11.0}";
}
sql.query(connectionString("DatabaseName"), "SELECT * FROM dbo.Table1" , (err, recordset) => {
if(err) {
// Do something with the err object.
return;
}
// else
// Do something with the recordset object.
return;
});
Below code is working for me......
const sql = require('mssql/msnodesqlv8')
// config for your database
var config = {
driver: 'msnodesqlv8',
server: 'serverNAme\\SQLEXPRESS',
database: 'Learn' ,
options: {
trustedConnection: true
}
};
It worked for me
need to install msnodesqlv8 and mssql. also .......:)
var dbConfig = {
driver: 'msnodesqlv8',
server: "DESKTOP-66LO4I3",
database: "FutureHealthCareWeb",
user: "sa",
password: "pass#123",
options: {
trustedConnection: true
},
debug: true,
parseJSON: true
};
var sql = require('mssql/msnodesqlv8');
sql.connect(dbConfig, function (err) {
if (err) { console.log(JSON.stringify(err)+'..............') }
else {
console.log('Connected')
}
}
);
this worked for me
const sql = require("mssql/msnodesqlv8");
const conn = new sql.ConnectionPool({
database: "DB name",
server: "server name",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
conn.connect().then((err) => {
if(err) throw err;
else console.log("connected");
const req = new sql.Request(conn)
req.query("select * from table", function(error, res){
console.log(res)
})
});
I struggled to connect with mssql server which run in remote windows server using windows authentication mode . Then i found the solution just used like below code.
sql.connect("Data Source=172.25.x.x,1433;User Id=CSLx\\Name;Password=xxxxxx1234;Initial Catalog=giveTHedataabseNamel;Integrated Security=True",function(err){ }
I've just add domain: "DNAME", in config, and as result this config helps me connect to MS SQL with windows auth.
const config = {
driver: 'msnodesqlv8',
domain: "DNAME",
user: 'username',
password: 'pass',
server: '7.6.225.22',
database: 'DBNAME',
requestTimeout: 3600000, //an hour
options: {
trustedConnection: true
},
debug: true,
parseJSON: true
};
This version doesn't need a username or password.
To use windows authentication I installed mssql and msnodesqlv8.
Then in my app.js file:
const mssql = require('mssql/msnodesqlv8');
Note it is mssql not sql if you're using this example.
var config = {
database:'YOUR DATABASE NAME',
server: 'localhost\\SQLEXPRESS',
driver: 'msnodesqlv8',
options: {
trustedConnection: true,
enableArithAbort: true
}
};
You need to change the database name in config. Other than that it should work. My example:
app.get('/', function (req, res) {
mssql.connect(config, function (err) {
if (err) console.log(err);
var request = new mssql.Request();
request.query('select * from dbo.visit', function (err, result) {
if(err) console.log(err);
console.log(result);
});
});
});

How can I share model methods between the client and the server in loopback?

I want to share some business logic both on the client and the server.
Let's say it is a file API, and I want to know if an item has a type of folder.
On the server it looks like this:
Content.prototype.isFolder = function() {
return this.type === 'folder';
}
Is it currently possible to expose this in an easy manner to the client?
We are also using loopback-sdk-angular. Integrating with that is the ultimate goal.
What is the best way to do this?
You can use browserify.
You can create a shared library that has the isFolder method, and use this both on the server, and the browserified version on the client.
How you easily integrate that with angular is another question.
I would suggest to create a new remote method, to expose it to the REST API:
Model.remoteMethod(
'isFolder',
{
http: { path: '/isFolder', verb: 'get' },
accepts: [
{
arg: 'id',
type: 'string',
required: true,
http: {
source: 'query'
}
},
],
returns: { arg: 'isFolder', type: 'boolean' }
}
);
Use the common directory at the project root. See http://docs.strongloop.com/display/public/LB/common+directory

Resources