Appcelerator Cloud Services Posts Object Query using AngularJS - angularjs

All,
I am using Appcelerator Cloud Services as my backend for an AngularJS/Ionic Framework/PhoneGap mobile app I am working on. I am trying to query the ACS Posts object by user_id and tags_array.
My code is at the following gist :
https://gist.github.com/bp4151/d6828f8d7af983316f99
I am formatting the query string as follows:
getByFriends: function(user_ids, tag) {
var query = "where={$and[{'user_id':$in['" + user_ids + "']},{'tags_array':$in['" + tag + "']}]}";
return $http.get('https://api.cloud.appcelerator.com/v1/posts/query.json?key=' + globals.ACSKey + '&query=' + query + '&_session_id = ' + globals.session_id);
},
I modified the code to the following, but I am still having no luck
getByFriends: function(user_ids, tag) {
//return $http.get('https://api.cloud.appcelerator.com/v1/posts/query.json?key=' + globals.ACSKey + '&query=' + query + '&_session_id = ' + globals.session_id);
return $http.get('https://api.cloud.appcelerator.com/v1/posts/query.json?key=' + globals.ACSKey + '&_session_id = ' + globals.session_id, {
params: {
query: "where={$and[{'user_id':$in['" + user_ids + "']},{'tags_array':$in['" + tag + "']}]}"
}
});
},
I expect only one post record to be returned with the id I am passing in (532f233f1316e90b760eca00) but I am getting all posts back no matter what I try. If anyone can point my in the right direction, I would really appreciate it.
Thanks,
Bruce

I figured it out. The issues are
the params block is not set up properly,
I need to decode the string that is being sent.
I was confused by the documentation that stated query: where=... The correct way to do this with Angular is as I coded it below using "where":...
get: function(user_id, tag) {
console.log('PostService.get');
return $http.get('https://api.cloud.appcelerator.com/v1/posts/query.json?key=' +
globals.ACSKey,
{
params: {
"where": decodeURIComponent('{"user_id": {"$in":["' + user_id + '"]},
"tags_array":"' + tag + '"}')
}
});
},

Related

obfuscated page content while using output cache in mvc 5

I'm developing a web application using MVC5 and I use output cache attribute on one of my actions.
the problem is after multiple page visits, my page will have binary content that looks like this:
page screenshot
there's my source:
[OutputCache(Duration = 86400, Location = OutputCacheLocation.ServerAndClient,VaryByParam = "ID;slug")]
[SeoOptionsFilter]
public ActionResult CourseDetail(int ID, string slug)
{
var courseComplexObject =
_courseRepository.GetCourseDetail(ID, slug);
var course = courseComplexObject.Model;
TempData["breadcrumb"] = BreadcrumbViewBuilder
.New().Home().Courses()
.AddMore(course.CategoryName, "/Category/" + course.CategoryId.ToString() + "/" + course.CategorySlug)
.AddMore(course.Name, "/CourseDetails/" + course.CourceId.ToString() + "/" + course.Slug + ".aspx",
true)
.Build();
//TODO: What if course is null
SetViewBagIfUserIsRegistered(course, ID);
TempData["CourseVideoCatOn"] = GetCourseVideoCategory(ID);
TempData["CourseID"] = ID;
TempData.Keep();
// Response.Cache.SetOmitVaryStar(true);
return View(courseComplexObject.Model);
}
I commented my custom action filter [SeoOptionsFilter]
but the result already has errors.
this error occurs randomly in page visits

DiscordJS V12 client.guilds.cache.get(...).emojis.forEach is not a function

let static = [], animated = [];
client.guilds.cache.get('911491194654175242').emojis.forEach(emoji => emoji.animated ? animated.push([emoji.id, emoji.name]) : static.push([emoji.id, emoji.name]));
console.log('Static Emojis\n');
static.forEach(emoji => console.log('<:' + emoji[1] + ':' + emoji[0] + '>'));
console.log('\nAnimated Emojis\n');
animated.forEach(emoji => console.log('<a:' + emoji[1] + ':' + emoji[0] + '>'));
This is my code for my ready event, I am trying to log all the emojis in my guild to the console to make my life easier but returns an error client.guilds.cache.get(...).emojis.forEach is not a function

undefined JSON object / Array Javascript

JSON Data
myData = {"data":[{"pre":1,"post":2}]}
JSON.stringify(myData) shows that data is an array with one element, an object.
console.log("type of data: " + typeof(myData));
console.log("data: " + JSON.stringify(myData));
console.log("data.pre: " + data.pre);
Log result
type of data: object
data: {"data":[{"pre":1,"post":2}]}
data.pre: undefined
I manually adjusted and added a JSON.
It works with this JSON (without the object)
myData = {"pre":1,"post":2}
and
console.log("data.pre: " + data.pre);
Log result
data.pre: 1
How can i achieve this? I want to use it later as a variable.
pre = data.pre;
post = data.post;
If your data inside an array you need to specify the index of the object you want to access ex: data[0].pre
myData = {"data":[{"pre":1,"post":2}]}
console.log("type of data: " + typeof(myData));
console.log("type of data: " + typeof(myData.data));
console.log("data: " + JSON.stringify(myData.data));
console.log("data.pre: " + myData.data[0].pre);
console.log("data.post: " + myData.data[0].post);

PostgresSql + Nodejs (ClaudiaJS) : How to cast array of string to array of timestamp

I am writing API which insert into a table with multiple rows, I am using UNNEST to make it work.
What I have done:
in js file:
api.post(PREFIX + '/class/insert', function (request) {
var db = pgp(dbconnect);
//Params
var data = request.body; //should be an array
var classes = [];
var starts = [];
var ends = [];
for (var i = 0; i < data.length; i++) {
classes.push(data[i].class_id);
starts.push(data[i].timestamp_start);
ends.push(data[i].timestamp_end);
}
const PQ = require('pg-promise').ParameterizedQuery;
var sql =
"INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
"VALUES( "+
"UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
"UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "), " +
"UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + ")"
const final_sql = new PQ(sql);
return db.any(final_sql)
.then(function (data) {
pgp.end();
return 'successful';
})
.catch(function (error) {
console.log("Error: " + error);
pgp.end();
});
}
Request body
[{
"class_id":"1",
"timestamp_start":"2017-11-14 14:01:23.634437+00",
"timestamp_end":"2017-11-14 15:20:23.634437+00"
}, {
"class_id":"2",
"timestamp_start":"2017-11-14 15:01:23.634437+00",
"timestamp_end": "2017-11-14 16:20:23.634437+00"
}]
When I run api in postman, I get the error is:
column "timestamp_start" is of type timestamp with time zone but
expression is of type text
Issue is obviously from ARRAY of string that I used in sql, my question is how to create ARRAY of timestamp for UNNEST, or any suggestion are appreciated.
Thanks
Never initialize the database inside the handler, see: Where should I initialize pg-promise
Never call pgp-end() inside HTTP handlers, it destroys all connection pools.
Use static ColumnSet type to generate multi-insert queries.
Do not return from db.any, there is no point in that context
You must provide an HTTP response within an HTTP handler
You are providing a confusing semantics for column class_id. Why is it called like that and yet being converted into a timestamp?
Never concatenate objects with strings directly.
Never concatenate SQL strings manually, it will break formatting and open your code to SQL injection.
Use Database methods according to the expected result, i.e. none in your case, and not any. See: https://github.com/vitaly-t/pg-promise#methods
Initialize everything needed only once:
const db = pgp(/*connection*/);
const cs = new pgp.helpers.ColumnSet([
'class_id',
{
name: 'timestamp_start',
cast: 'timestamp'
},
{
name: 'timestamp_end',
cast: 'timestamp'
}
], {table: {table: 'class', schema: 'sa1'}});
Implement the handler:
api.post(PREFIX + '/class/insert', request => {
const sql = pgp.helpers.insert(request.body, cs);
db.none(sql)
.then(data => {
// provide an HTTP response here
})
.catch(error => {
console.log('Error:', error);
// provide an HTTP response here
});
}
Many thanks to #JustMe,
It worked after casting array
var sql =
"INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
"VALUES( "+
"UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
"UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "::timestamp[]), " +
"UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + "::timestamp[])"

NodeJS OracleDB bind parameters returning parameter name

I am very new to NodeJS, but I have been working to use it to serve my Angular project. I need to access an Oracle DB and return some information using a select statement. I have one statement that works correctly using a bind parameter that is set up like this:
var resultSet;
connection.execute("SELECT column_name, decode(data_type, 'TIMESTAMP(3)','NUMBER'"
+ ",'VARCHAR2','STRING','CHAR', 'STRING','NUMBER') as \"DATA_TYPE\""
+ "FROM someTable where table_name = :tableName",
[table], //defined above
{outFormat: oracledb.OBJECT},
function (err, result) {
if (err) {
console.error(err.message);
doRelease(connection);
return;
}
resultSet = result.rows;
console.log("Received " + resultSet.length + " rows.");
res.setHeader('Content-Type', 'application/json');
var JSONresult = JSON.stringify(resultSet);
// console.log(JSONresult);
res.send(JSONresult);
doRelease(connection);
});
This returns exactly what I want it to, with the bound variable being what I wanted it to be. Below is the code that doesn't work:
var resultSet;
connection.execute(
"SELECT DISTINCT :columnName from someTable",
['someColumn'],
{outFormat: oracledb.OBJECT},
function (err, result) {
if (err) {
console.error(err.message);
doRelease(connection);
return;
}
resultSet = result.rows;
console.log("Received " + resultSet.length + " rows.");
res.setHeader('Content-Type', 'application/json');
var JSONresult = JSON.stringify(resultSet);
console.log(JSONresult);
res.send(JSONresult);
doRelease(connection);
});
This returns {":COLUMNNAME": "someColumn"}. I do not understand why it won't display the results correctly. The two snippets of code are exactly the same, save the SQL query part. I know this a long question, but I really need help. Thank you!
You can bind data values, not the text of the statement itself.

Resources