GetStream.io - Delete a feed nodejs - javascript

I am using Getstream.io nodejs module.
I am creating feeds at run time and want to know if there is a way to delete a feed through code?.
I see in the code base that there is a delete interface but when I looked in to RESTFul API documentation, I did not find any end point to delete a feed.
But when I look at Ruby documentation, I see that there is way to delete a feed.
Please let me know how can I achieve deleting a feed in getstream.io from nodejs

I was able to delete a feed using nodejs. It is just a hack but it will work.
But remember that deleting a feed means, it deletes all the activities from the feed. The feed still exists and can be seen through databrowser. The follow/following relationship still exists.
DeleteFeed = function(params,callback){
if (params.feedId) {
var feed = client.feed(params.feedType, params.feedId);
//remove followings
feed.following({limit:25,offset:0},function(err,r){
if (!err) {
for (var i = 0; i < r.body.results.length; i++) {
var tempFeed = r.body.results[i].target_id.split(':');
feed.unfollow(tempFeed[0], tempFeed[1]);
}
}
});
// do something similar as followings for followers
//(I did not have to worry about it hence did not write any code)
client.delete({
url: "feed/" + params.feedType + "/" + params.feedId + "/",
signature: feed.signature
}, function (e, r) {
//DO NOTHING
//console.log("Error -- " + e);
//console.log("Result -- " + JSON.stringify(r,null,2));
});
}
};

The delete operation is currently not supported by the nodejs client library. There is an api endpoint that supports this operation: feed, but the delete operation is not documented on the REST docs. You can delete feeds from the databrowser on the getsream.io dashboard.

You can achieve such thing by doing doing the logical delete behavior by:
modeling the feeds design to have a logical delete
use as must TO field as possible, so you can remove all activities of feeds added by To targeting field automatically
consider a follow feed design. Instead of remove activities you can just unfollow the deleted feed
map the foreign_id field properly in order of batching delete

Related

Let Strapi CMS create pages based on html template file

So probably my explanation is awful, but i really don’t know how to express my problem or what to search for.
I got a site (www.example.com/blog.html) showing all blog post entries created in a headless cms (Strapi). The site receives the posts by making an url request and parsing the resulting JSON data. This data also contains an unique url slug for each post serving as an identifier.
I want to create one page for each blog post created in the headless cms based on a „template“ html.
What I tried is passing the urlslug as a url parameter (www.example.com/blog/article.html?id=*URLSLUG*) and then using this url parameter to fetch the corresponding post data from the cms. I followed this guide: https://strapi.io/blog/build-an-editorial-website-with-vanilla-java-script-and-strapi
It works, but I don’t want to rely on url parameters for seo reasons. Instead I want something like www.example.com/blog/*URLSLUG*. In other words: I want to have one page for each blog post entry in my headless cms based on a „template“ html.
Any suggestions?
Code can be added if necessary
well there is few options here:
The first one is most reliable, and easy but seems not that fancy as you want:
https://market.strapi.io/plugins/strapi-plugin-slugify
The main reason to use this solution is that it handles slug creation when you create post via REST api. The uuid field needs extra work when post created not from admin panel.
So second option is do it yourself style:
/api/article/controller/article.js
module.exports = createCoreController('api::article.article', ({strapi}) => ({
findOne(ctx){
const { slug } = ctx.params;
return strapi.db.query('api::article.article').findOne({where: {slug});
}
});
then in the routes create routes.js file
/api/article/routes/routes.js
module.exports = {
routes: [
{
method: 'GET',
path: '/articles/:slug'
handler: 'article.findOne'
}
]
}
then if you want to create articles for outside of admin, create lifecycles.js in
/api/article/content-types/article/lifecycles.js
module.exports = {
async beforeCreate(event) {
// here you have to do something like
let slug = slugify(event.result.name);
let isNotFree = await strapi.db.query("api::article.article").findOne({where: {slug}});
if (Boolean(!isNotFree)) // < not sure prolly need an empty object check
for (let i = 1; i < 9999 ; i++) {
slug = `${slug}-${i}`;
isNotFree = await strapi.db.query("api::article.article").findOne({where: {slug}});
if (Boolean(!isNotFree))
break;
}
event.result.slug = slug
}
}
pleas note the lifecycle code is just a first thing came to my mind, should be tested and optimized prolly
the implementation gives you the findOne controller, you gonna need to do it for each other update, delete, etc...

$.getJSON works when trying to find all records, but doesnt work when trying to find one specific record

I'm working on a section of my app where a user can add a note to his project. Each note has the capability to have additional comments appended to it.
So far the backend is working. When calling all records at a time or one record at a time(by id) manually, be it via postman or simply adding the id number of a project(gotten from mongo) to the browser, both pull up the records as specified.
The problem starts when I try to pull this information through the front end via
$.getJSON.
Say for example that I have two projects in my app.
Project 01 has an id of "123" and has 3 comments
and
Project 02 has an id of "456" and has 10 comments
When I call all projects on the front end of the app, I see both appear, and all their comments come through ok but when I try to call, for example, project two by id, it does show but I get 10 "undefined" for all of that projects 10 comments. Same thing happens for any one record I call.
And again, this happens only when trying to call it via jquery $.getJSON because when I manually do it via postman/browser, they come through fine.
Here is some code below for when I try to find one record (not working fully).
This is the backend code:
app.get("/notesapi/:tabID", (request, response) => {
var idNum = request.params.tabID;
var newIdNumber = idNum.trim();
NotesModel.findOne({_id: newIdNumber}, (error, data)=>{
if(error){
console.log("error in finding this particular record!");
throw error;
} else {
console.log("data for this one record found YO");
response.status(200);
response.json(data);
}
});
});
And this is the front end code:
function getFreshComments(tabID){
console.log("FRONTEND -- the link is: /notesapi/" + tabID);
$.getJSON("/notesapi/456", showCommentsGotten);
function showCommentsGotten(dataFedIn){
var tabInnerComments = $("#" + tabID +" .theNote");
var output = "";
$.each(dataFedIn, (key, item)=>{
output += item.todoMessages + "<br>";
});
var normalComments = output;
var newComments = normalComments.split(",").join("<br>");
tabInnerComments.html(newComments);
}
}
As the example explained above, if I wanted to pull the 10 comments from id 456, then when I use $.getJSON("/notesapi/456", showCommentsGotten);
This returns me 10 "undefined".
When I remove the id number from the URL, then it fetches me ALL the comments for ALL the notes.
I don't get any errors anywhere. What am I missing or doing wrong?

Firebase Database workouts issues

I created the Database in firebase and used for my hybrid application, Let you explain the application scenarios below.
I have a hybrid application in this app, We need to insert, update, delete, kind of operations using firebase.
As of now, I did the insert method kind of queries alone using code. So the thing is I want to create multiple tables in firebase is it possible ?
Because For example, I've userTable, adminTable and guestTable, So If I need to insert one userData before that I need to check already the user found or not in Admin table this kind of scenarios How can I do in firebase ?
How can I maintain multiple tables in the firebase Database dashboard?
I have the table name called "Inmate_Data" now I want to add one more Table called "Admin_Data" and How can I do a joint operation like connecting two table using Firebase.
And, I tried to add one more table using Import JSON option But while I inserting new JSON the old Table got deleted like the "Inmate_Data" deleted and new JSON got added.
Please guide me in this.
#FrankvanPuffelen - Please find the below coding part.
Actually, I created the form and saving the data into firebase using below code.
$scope.addInmateDataToFirebase = function() {
alert('Firebase')
var newPostKey = null;
// Get a key for a new Post.
newPostKey = firebase.database().ref().child('Tables/Inmate_Data').push().key;
alert(newPostKey);
var dateofjoin= $filter('date')($scope.IMDOJ, 'yyyy-MM-dd');
var dateofbirth= $filter('date')($scope.IMDOB, 'yyyy-MM-dd');
console.log("Result"+ newPostKey);
var admissionId="KAS"+pad(newPostKey,5);
console.log("Padded number"+ pad(newPostKey,5));
alert(admissionId);
// A post entry.
var postInmateData = {
Inmate_ID: admissionId,
Inmate_Name: $scope.IMfirstnameText,
Inmate_Perm_Address1: $scope.IMAddress1 ,
Inmate_Perm_Address2: $scope.IMAddress2 ,
Inmate_Perm_City: $scope.IMCity,
Inmate_Perm_State: $scope.IMState,
Inmate_Perm_Pincode: $scope.IMPincode,
Inmate_ProfilePhotoPath: $scope.IMProfilePhotoPath,
Inmate_Temp_Address1: $scope.IMLocAddress1,
Inmate_Temp_Address2: $scope.IMLocalAddress2,
Inmate_Temp_City:$scope.IMGcity,
Inmate_Temp_State: $scope.IMGstate,
Inmate_Temp_Pincode: $scope.IMGpincode,
Inmate_Mobile: $scope.IMMobile,
Inmate_DOB: dateofbirth,
Inmate_EmpOrStudent: $scope.IMEmpStudent,
Inmate_DOJ: dateofjoin,
Inmate_ID_Type: $scope.IMIdcardType,
Inmate_ID_No: $scope.IMIdcardno,
Inmate_ProffPhotoPath: $scope.IMProofPhotoPath,
Inmate_Status:$scope.IMStatus
};
// Write the new post's data simultaneously in the list.
var updates = {};
updates['/Tables/Inmate_Data/' + newPostKey] = postInmateData;
return firebase.database().ref().update(updates).then(function() {
//$scope.ClearInMateDetails();
alert(admissionId);
$scope.statusMessage = "Welcome to Kasthuri Hostel. Your Admission ID is" + admissionId +" . Enjoy your Stay.";
//sendSMS('9488627377',$scope.statusMessage);
alert('Inmate data stored in cloud!');
$scope.ClearInMateDetails();
}, function(error) {
alert (error);
});
}
Now the Inmate_data got stored. and I need to save the Inmate_alloc_data into firebase but before that, I need to check whether the Inmate_Id available in the Inmate_Data table in firebase.
Please find the below snap :
My suggestions :
For example like above screenshot now I've multiple tables like "Inmate_Data", "Inmate_Alloc", and more Shall I get all the data and store it in a local SQLite Db like same as "Inmate_Alloc_tbl" and "Inmate_Data_tbl" and finally If I update any values finally I want to get all values in the local database and store it in the firebase. Is it possible to handle ?
If so I can manage lots of SQL queries, right ? Because via firebase we can't able to manage all queries right ?
Please suggest your ideas.

Looking for a Cloud Code ( javascript ) expert, dealing with Installations and channels

So my biggest problem is that I never wrote a single line of javascript before but as I developing my application it has become more and more clear I have to use it in Cloud Code.
I have a parse class named Groups, in this I store groups with the following data:
Name, Description, Users, Requests.
If a user creates a group from their device it will be here with the given name, description and the user pointer in it, and I'm using the new objectId with a + "C" char (sometimes objectId starts with a number but its not valid for a channal) to subscripte that user ( installation ) to a channel, so if I query the groups, I get the objectId and I can send every member of the group a push notification.
My first problem is here, that if i store the channel to a installation object in parse with the following code:
groups = new Groups();
groups.setName(groupName.getText().toString());
groups.put("members", ParseUser.getCurrentUser());
groups.setDesc(description.getText().toString());
groups.saveEventually(new SaveCallback() {
#Override
public void done(ParseException e) {
//Subscribe to push
ParsePush.subscribeInBackground("C" + groups.getObjectId(), new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.d("com.parse.push",
"successfully subscribed to the broadcast channel.");
} else {
Log.e("com.parse.push", "failed to subscribe for push", e);
}
}
});
If the user has multiple devices then he wont get the push notifications on every device just on that where he created the group. I searched for it and I am sure I have to use a Parse Cloud function for the subscribing process and with it all the Installations of a specific user will subscribe to the same channels.
Here is my first problem. Can anyone help with it or just give me some reference to solve this (I read all the Cloud Documentation)
Notice:
After the registration I add the user pointer to the Installation like this:
ParseInstallation.getCurrentInstallation().put("user", ParseUser.getCurrentUser());
My second problem:
As I find others have problem with it too and there was some solutions but my problem is a bit more complex. So as I noticed, if I send a client side notification from a device, it will be delivered to the selected channels, it working fine, but if I delete the application then reinstall it, and I'm sending client side notification, it wont delete the multiple installation objects for the device and I will get the notification twice
(I know that if I send notification from parse dashboard it is doing the delete job).
So I need a cloud function that is checking that if there is an other installation with the same user and androidId ( added at install, get it from Android Security ) , if there, then delete it, check if there is an other installation with the same user but not with the same andoidId, copy that installation's channels to my new one and then save the new installation.
Same as above, reference, example code, anything.
I think it will be usefull for others too and hope that someone can help me.
(P.S.: If you need more information please comment, I will always answer in 24 hours)
Whenever the app opens, make sure that the device subscribes to the channel:
"user_" + ParseUser.getCurrentUser().getObjectId()
Then you will send the push notifications to all the devices that the user is signed into.
First problem solution:
I am showing the Groups in a listView, and when a new group is added, the list have to refresh itself, it do it with this method:
public static void updateData() {
ParseQuery<Groups> query = ParseQuery.getQuery("Groups");
query.whereEqualTo("members", ParseUser.getCurrentUser());
query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
query.findInBackground(new FindCallback<Groups>() {
#Override
public void done(List<Groups> parseObjects, ParseException e) {
if(e != null) {
return;
}
for( int i = 0; i < parseObjects.size(); i++){
Groups iter = parseObjects.get(i);
ParsePush.subscribeInBackground("C" + iter.getObjectId());
}
groupsAdapter.clear();
groupsAdapter.addAll(parseObjects);
}
});
}
With this method (added to onResume) every time I resume to the application it refreshes the list and the device subscribing to all the channels created from the objectId's of the groups where he is a member.
I know it is not a well solution but for now it is fine for me.
And still looking for a better one and for my second question.

How do I access the data given in the onHttpRequest function in the Firefox Add-on SDK?

I am trying to read the response headers 'name' and 'value'. The end goal is to compare them to some pre-set name and a value to see if they match.
Here is what I have so far, it's the function that run every time I get a response header.
var observer = require("observer-service");
observer.add("http-on-examine-response", onHttpRequest);
function onHttpRequest(subject, data)
{
console.log("request subject...." + subject);
console.log("request data...." + data);
}
The output is as follows:
request subject....[xpconnect wrapped nsISupports]
request data....null
I was hoping to know how to get the rest of the data out of the response.
Any help would be great, thanks.
The subject for http-on-examime-response implements nsIHttpChannel, among some other things. You may use .QueryInterface() or instanceof (which internally kinda uses QueryInteface, so that this works as well) to get to that interface.
const {Ci} = require("chrome");
if (subject instanceof Ci.nsIHttpChannel) {
console.log("content-type", subject.getResponseHeader("content-type"));
subject.visitResponseHeaders(function(header, value) {
console.log(header, value);
});
}
There are a couple of other questions around here going into more detail on how to use these notifications... Also, mxr can help a lot checkout out what interfaces there are, how it fits together and how one could use it (in particular the existing tests are great to see some uses for all kinds of stuff).
There is also the "nsITraceableChannel, Intercept HTTP Traffic" article going into more details, e.g. on how to use nsITraceableChannel to get the payload data from such a channel.

Categories