Delete JSON data via JavaScript - javascript

I'm creating a discord bot for a server with a few friends - I have a warn system and level system.
I've managed to get the JavaScript to write to the external JSON file.
{
"other-users": "other-user-data",
"304937039483493847": {
"amount": 1,
"id": "<#304937039483493847>",
"username": "Jered",
"reasons": {
"first-reason": "test"
}
},
"other-users": "other-user-data"
}
I've managed to get the data to change from warnings to remove warnings, but I need to delete the whole 304937039483493847 object from the file.
What would be the best way to do that?

I hope it is what you need.
let data = {
"304937039483493847": {
"amount": 1,
"id": "<#304937039483493847>",
"username": "Jered",
"reasons": {
"first-reason": "test"
}
},
"other-users":"other-user-data"
};
console.log(data);
delete data["304937039483493847"];
console.log(data);

Related

Google App Script - Save the sheet file Id created from my sheet file template

thank you for the time you will take to resolve my issue !
I am not sure that Google app script allows to do what I need.
Could you please tell me if it is possible?
If yes, do you have already a script code to do it?
I have created a file which I have shared it with others colleagues (in a shared drive), and it is used as a "template".
When a colleague creates a copy of it, I would like that the script to give me the new Google sheet id created from the model and saved this id in my Google sheet dashboard?
Is it possible with appscript?
Thanks a lot and have a good day !
Copy Spreadsheet and Save Id
function copySpreadsheetAndSaveId() {
const fileId = "fileid";
const ss = SpreadsheetApp.getActive():
const sh = ss.getSheetByName("Dashboard");
sh.getRange(sh.getLastRow() + 1, 1).setValue(DriveApp.getFileById(fileId).makeCopy().getId());//appends the id to the bottom of column one in the sheeet named Dashboard.
}
If you want users to be able to open the Spreadsheet then you can't restrict them copying it by script only
I can think of a couple of workarounds:
Workaround 1:
Make the Spreadsheet private, and create a web app which runs as you but is accessible by other users. On doGet(), create a copy of the Spreadsheet and share it with the email returned from Session.getActiveUser().getEmail():
function doGet() {
// Check if security policy gets email address:
const user = Session.getActiveUser()
if (!user.getEmail()) {
return ContentService.createTextOutput('Unable to retrieve user.')
}
const ss = DriveApp.getFileById("template-spreadsheet-id")
const newFile = ss.makeCopy().addEditor(user)
const html = `File copied, click here to open.`
return HtmlService.createHtmlOutput(html)
}
Pros:
Should work for anyone within the same domain as you
You can directly retrieve the ID on copy and save it to your database
Cons:
Security policy might stop you being able to get the user
What's to stop them from just copying the copy?
Workaround 2:
If you're an admin user, you could use the Drive Audit Activity API to check for domain-wide copy events of a given file ID. It's a bit more involved and assumes you have a client set up in GCP but will have a bigger catch-radius than the first workaround, and also doesn't involve restricting access to the template or creating a Web App:
function getAuditLog() {
const baseUrl = "https://admin.googleapis.com/admin/reports/v1/activity/users/all/applications/drive"
const apiKey = "api-key-obtained-from-gcp"
const params + `eventName=copy&key=${apiKey}`
const headers = {
"Authorization": `Bearer ${ScriptApp.getOAuthToken()}`,
"Accept": "application/json"
}
const response = UrlFetchApp.fetch(`${baseUrl}?${params}`, {
"method": "get",
"headers": headers"
})
const responseData = JSON.parse(response.getContentText())
}
You'll then have to process the response. responseData contains an items key which is an array of copy events in the audit report:
{
"kind": "admin#reports#activities",
"etag": "\"xxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxx\"",
"items": [
{
"kind": "admin#reports#activity",
"id": {
"time": "2022-01-21T10:03:12.793Z",
"uniqueQualifier": "-XXXXXXXXXXXXXX",
"applicationName": "drive",
"customerId": "xxxxxxx"
},
"etag": "\"xxxxxxxxxxxxx/xxxxxxxxxxx\"",
"actor": {
"email": "user#example.com",
"profileId": "XXXXXXXXXXXX"
},
"ipAddress": "0000:0000:0000:0000:0000:0000:0000:0000",
"events": [
{
"type": "access",
"name": "copy",
"parameters": [
{
"name": "primary_event",
"boolValue": false
},
{
"name": "billable",
"boolValue": true
},
{
"name": "old_value",
"multiValue": [
"Spreadsheet Template File Name"
]
},
{
"name": "new_value",
"multiValue": [
"Copy of Spreadsheet Template File Name"
]
},
{
"name": "doc_id",
"value": "new-spreadsheet-id"
},
{
"name": "doc_type",
"value": "spreadsheet"
},
{
"name": "is_encrypted",
"boolValue": false
},
{
"name": "doc_title",
"value": "Copy of Spreadsheet Template File Name"
},
{
"name": "visibility",
"value": "private"
},
{
"name": "actor_is_collaborator_account",
"boolValue": false
},
{
"name": "owner",
"value": "user#example.com"
},
{
"name": "owner_is_shared_drive",
"boolValue": false
},
{
"name": "owner_is_team_drive",
"boolValue": false
}
]
}
]
}
]
...
}
You will have to filter out the reponse from here, however. For each element in the items array, the events key contains the information you will need to look for:
old_value is the original template spreadsheet's name
doc_id is the ID of the new spreadsheet
items.actor is the email of the person that completed the action.
References:
Example Audit request using the Try this API feature

unable to perform CRUD in JSON-SERVER

I am trying to add, update, delete in JSON server with Redux Axios. But I am unable to perform CRUD action. I am always getting an error 404. I am using the following code example. this my db.json
{
"orderdetails": [
{
"OrderID": 111,
"CustomerID": "VINET",
}
]
}
I am using the following code for importing Axios from redux. Please find my server.js
import axios from 'axios';
export default axios.create({
baseURL: "http://localhost:3007/",
headers: {
"Content-type": "application/json"
}
})
I am using the following code example for performing CRUD action in the JSON-Sever. But, I am got a error
import http from "../serverapi";
create(data) {
return http.post("/orderdetails/posts", data);
}
update(id, data) {
return http.put(`/orderdetails/${id}`, data);
}
delete(id) {
return http.delete(`/orderdetails/${id}`);
}
could you please provide the suggestion?
If you are using the json-server npm package, there are a couple of problems with your usage.
First, you db.json is invalid. It should be somewhat like this:
{
"orderdetails": [
{
"OrderID": 111,
"CustomerID": "VINET"
},
{
"OrderID": 12,
"CustomerID": "VINET"
}
]
}
Make sure to check the API url in the browser first.
Second, json-server by default runs on localhost:3000 (Not sure if it can be changed, check the docs here https://www.npmjs.com/package/json-server). Your API is pointing to port 3007 as seen here baseURL: "http://localhost:3007/,
Lastly, you cannot do a request like http://localhost:3000/orderdetails/111. The last part in the api url by default corresponds to the id key in db.json, but since your key is OrderID, your API end point should be modified to http://localhost:3000/orderdetails?OrderID=111. Try this url in your browser, it should return the correct object.
UPDATE
Update operations in json-server require the id key to be present in the db.json file. Hence, update your db.json as follows:
{
"orderdetails": [
{
"id": 1,
"OrderID": 111,
"CustomerID": "VINET"
},
{
"id": 2,
"OrderID": 12,
"CustomerID": "VINET"
}
]
}
Then, you can try running a POST request on the url http://localhost:3000/orderdetails and json body :
{
"OrderID": 12333,
"CustomerID": "VINET"
}
This will create a new object in the db, with incremented id. PUT, DELETE requests can be made using the id param in the url like http://localhost:3000/orderdetails/3.

How to get JSON payload sent by the Slack action message?

I am trying to build a Slack bot with interactive buttons. I have set up a Google Apps Script to handle the action performed on the Slack message. I want the payload of the request sent by the Slack. I have tried to get the request object by doing
function doPost(e) {
return processComment(e);
}
function processComment(e) {
Logger.log(e);
}
{postData=FileUpload, queryString=method=slack, parameter={method=slack, payload={"type":"block_actions","user":{"id":"U01835Mxxxx","username":"ravsamteam","name":"ravsamteam","team_id":"T0160UQZZZZ"},"api_app_id":"A018MPZ2xxx","token":"NTNRCTPDz8mxxxzxxxxxxxxx","container":{"channel_id":"C0190D8L2AU","is_ephemeral":false,"message_ts":"1597154895.001500","type":"message"},"trigger_id":"1281039280903.1204976558018.aa1055f6900d7884d9cd4ac34ffzzzzz","team":{"id":"T0160UQGE0J","domain":"ravsamhq"},"channel":{"id":"C0190D8L2AU","name":"blogs"},"message":{"type":"message","subtype":"bot_message","text":"This content can't be displayed.","ts":"1597154895.001500","bot_id":"B019BNL08BS","blocks":[{"type":"section","block_id":"mNavk","text":{"type":"mrkdwn","text":" New comment on RavSam's blog by hello","verbatim":false}},{"type":"section","block_id":"v3Ip","text":{"type":"mrkdwn","text":"*Blog:*\nhello\n\n*Comment:*\nravgeet errorCannot read property 'payload' of undefined","verbatim":false}},{"type":"actions","block_id":"1maVO","elements":[{"type":"button","action_id":"WSo=","text":{"type":"plain_text","text":"Approve","emoji":true},"style":"primary","value":"approved"},{"type":"button","action_id":"Vek\/","text":{"type":"plain_text","text":"Deny","emoji":true},"style":"danger","value":"denied"}]}]},"response_url":"https:\/\/hooks.slack.com\/actions\/T0160Uxxxxx\/1301968xxxxxx\/Q3gZhbeUCUIxxxxxxxxxxxxx","actions":[{"action_id":"WSo=","block_id":"1maVO","text":{"type":"plain_text","text":"Approve","emoji":true},"type":"button","value":"approved","action_ts":"1597213837.152704"}]}}, contentLength=2391.0, parameters={payload=[Ljava.lang.Object;#53f2e9fa, method=[Ljava.lang.Object;#5793298b}, contextPath=}
How do I get the payload? Once I have the payload JSON, I can use the actions to determine what action was taken by the user?
Yes. The payload contains all the information you need to identify the action. And it also contains a response_url to respond back.
Slack payload should look like this.
{
"actions": [
{
"name": "channels_list",
"selected_options": [
{
"value": "C012AB3CD"
}
]
}
],
"callback_id": "select_simple_1234",
"team": {
"id": "T012AB0A1",
"domain": "pocket-calculator"
},
"channel": {
"id": "C012AB3CD",
"name": "general"
},
"user": {
"id": "U012A1BCD",
"name": "musik"
},
"action_ts": "1481579588.685999",
"message_ts": "1481579582.000003",
"attachment_id": "1",
"token": "iUeRJkkRC9RMMvSRTd8gdq2m",
"response_url": "https://hooks.slack.com/actions/T012AB0A1/123456789/JpmK0yzoZDeRiqfeduTBYXWQ",
"trigger_id": "13345224609.738474920.8088930838d88f008e0"
}
You can learn more here.

Optimalization of firebase query. Getting data by ids

I'm new in Firebase. I would like to create an app (using Angular and AngularFire library), which shows current price of some wares. I have list all available wares in Firebase Realtime Database in the following format:
"warehouse": {
"wares": {
"id1": {
"id": "id1",
"name": "name1",
"price": "0.99"
},
"id2": {
"id": "id2",
"name": "name2",
"price": "15.00"
},
... //much more stuff
}
}
I'm using ngrx with my app, so I think that I can load all wares to store as an object not list because normalizing state tree. I wanted load wares to store in this way:
this.db.object('warehouse/wares').valueChanges();
The problem is wares' price will be refresh every 5 minutes. The number og wares is huge (about 3000 items) so one response will be weight about 700kB. I know that I will exceed limit downloaded data in a short time, in this way.
I want limit the loading data to interesing for user, so every user will can choose wares. I will store this choices in following way:
"users": {
"user1": {
"id": "user1",
"wares": {
"id1": {
"order": 1
},
"id27": {
"order": 2
},
"id533": {
"order": 3
}
},
"waresIds": ["id1", "id27", "id533"]
}
}
And my question is:
Is there a way to getting wares based on waresIds' current user? I mean, does it exist way to get only wares, whose ids are in argument array? F.e.
"wares": {
"id1": {
"id": "id1",
"name": "name1",
"price": "0.99"
},
"id27": {
"id": "id27",
"name": "name27",
"price": "0.19"
},
"id533": {
"id": "id533",
"name": "name533",
"price": "1.19"
}
}
for query like:
this.db.object('warehouse/wares').contains(["id1", "id27", "id533"]).valueChanges();
I saw query limits in Angular Fire like equalTo and etc. but every is for list. I'm totally confused. Is there anyone who can help me? Maybe I'm making mistakes in the design of the app structure. If so, I am asking for clarification.
Because you are saving the ids inside user try this way.
wares: Observable<any[]>;
//inside ngOnInit or function
this.wares = this.db.list('users/currentUserId/wares').snapshotChanges().map(changes => {
return changes.map(c => {
const id = c.payload.key; //gets ids under users/wares/ids..
let wares=[];
//now get the wares
this.db.list('warehouse/wares', ref => ref.orderByChild('id').equalTo(id)).valueChanges().subscribe(res=>{
res.forEach(data=>{
wares.push(data);
})
});
return wares;
});
});
There are two things you can do. I don't believe Firebase allows you to query for multiple equals values at once. You can however loop over the array of "ids" and query for each one directly.
I am assuming you already queried for "waresIds" and you've stored those ID's in an array named idArray:
for id in idArray {
database.ref('warehouse/wares').orderByChild('id').equalTo(id).once('value').then((snapshot) => {
console.log(snapshot.val());
})
}
In order to use the above query efficiently you'll have to index your data on id.
Your second option would be to use .childChanged to get only the updated data after your initial fetch. This should cut down drastically on the amount of data you need to download.
Yes , you can get exactly data that you want in firebase,
See official Firebase documents about filtering
You need to get each waresID
var waresID = // logic to get waresID
var userId = // logic to get userId
var ref = firebase.database().ref("wares/" + userId).child(waresID);
ref.once("value")
.then(function(snapshot) {
console.log(snapshot.val());
});
this will return only data related to that waresID or userId
Note: this is javascript code, i hope this will work for you.

Firebase - how to find all the match items with auto-generated ID, where values are false

Following the techniques on https://www.firebase.com/docs/web/guide/structuring-data.html
Given the url root is: https://myApp.firebaseio.com
And the data is:
// Tracking two-way relationships between users and groups
{
"users": {
"mchen": {
"name": "Mary Chen",
"groups": {
"alpha": true,
"bob": false, // <- I want this
"charlie": true,
"dave": false // <- I want this
}
},
...
},
"groups": {
"alpha": {
"name": "Alpha Group",
"members": {
"mchen": true,
"hmadi": true
}
},
...
}
}
Is it possible to construct a Firebase query to find all the groups that have the value 'false' for user "mchen" (basically I want bob and dave)? How?
e.g. new Firebase('https://myApp.firebaseio.com/users/mchen/groups') ...
In my real code, alpha, bob, charlie and dave are Firebase auto-generated keys, but the same query should solve my problem. (I'm using Firebase Web version)
Thanks in advance.
Finally got it working. I'm not an expert, but I hope this helps anybody not familiar with Firebase:
If you only use Firebase:
var ref = new Firebase('https://myApp.firebaseio.com/users/mchen/groups');
ref.orderByValue().equalTo(false).on('value', function(data){
console.log(data.val());
})
If you use AngularFire:
var ref = new Firebase('https://myApp.firebaseio.com/users/mchen/groups');
$firebaseArray(ref.orderByValue().equalTo(false)).$loaded().then(function(data){
console.log(data);
});
Note:
orderByValue() is the one to use without knowing the keys
Use equalTo(false), not equalTo('false')
$firebaseArray is the one that returns multi items, not $firebaseObject
A rule is also required for performance:
{
"rules": {
"users": {
"$userName": { // A better way would be using an auto-generated ID in here
"groups": {
".indexOn" : ".value" // add index on the value - notice it's .value
}
}
}
}
}

Categories

Resources