HTTP Request - Delete JSON file key in Firebase with Axios - javascript

I have a firebase database setup with an orders.json file created. I already have it setup to where I can post an order to the json file from a javascript project, and then firebase assigns a unique key which looks like "-LKx1RmbvyruM8-5S2mo". I would like to delete a single order based off of that unique identifier key via http request and query params without deleting the entire orders.json file. I'm also using authentication, so my request would look like this:
axios.delete('https://myproject-37b7d.firebaseio.com/orders.json?auth=mytoken')
This would of course delete the entire json file which I do not want. Would I put the unique key in the url query params somehow? Or in the axios config? I figured out how to console log it in a GET request via the .get().then(res => console.log(res.data["-LKx1RmbvyruM8-5S2mo"]))
I tried reading through firebase's api and not many good examples. Any help is much appreciated]1
u

Due to firebase database is a simple json-like object, and single order is an object too, with its own link, I simply make a delete request like that:
removeOrderHandler = (orderId) =>{
axios.delete("/orders/" + orderId +".json?auth=" + this.props.token)

Related

Fetching and hashing a file from a URL in a Zapier code action in JavaScript

I was looking for a way to hash files manipulated in a Zapier code action and since Zapier does not provide such crypto transforms by default, I went on to implement it in Javascript.
The code below does this:
fetch the file from a public URL
hash said file using sha256
return the hash in the output
const crypto = require('crypto');
return fetch(inputData.fileUrl)
.then((res)=>{
console.log(res.ok);
console.log(res.status);
console.log(res.statusText);
return res.buffer()
})
.then((buffer)=>{
const hash = crypto.createHash('sha256');
hash.update(buffer);
callback (null, {"hashValue":hash.digest('hex')});
})
.catch(callback)
I am basically calling 'fetch' on the S3 URL, returning the result as a buffer() call on the response object. I then create a 'crypto' object from said buffer, from which I create a sha256 hash and hex digest.
Note:
Javascript code actions in Zapier can only take strings as input parameters, so any files you want to hash need to transit through a storage space (e.g. AWS S3 bucket) that has a publicly accessible URL. If you manipulate private/sensitive data, you may want to delete the file in a subsequent action in your zap. Beware also of non ascii characters in the URL (e.g. fetching from AWS S3 returns a 403 Forbidden error if your URL includes such characters as '€')
I hope Zapier users will find this useful, e.g. to automate workflows where you need to ensure file data integrity (accounting, invoicing ...)

How to get around auth level when testing API on laravel project?

I am using the basic Auth from laravel that you get from running the following command.
php artisan make:auth
I have an API written so that the backend on the server can update/create services and statuses. The issue i'm running into is that the Admin also has a UI on the web app and can create a service, or update its status manually. Therefore, I have an Auth level on the methods where you have to be logged in to use them.
Now when I call the method in postman it redirects me to the login page, I was wondering if there was a way around this Auth level strictly for an API?
I was told of a way to do pre-request scripts directly in postman but i'm fairly lost when it comes to the whole java script part of that and feel like there is an easier way to do it. I also already tried to do 'basic auth' with the username and password, it didnt seem to work though.
Thank you for the help in advance!
Edit: Here is the screenshot from my header.
I am presuming if you have the API in place you have an api_token set for the specific user. You can use that inside Postman in one of two ways.
You will goto the Headers tab and add:
Key: Authorization
Value: Bearer API_TOKEN_VALUE
Edited: Added the screenshot of postman
You can amend the url for the request and add the token:
url_to_api_endpoint?api_token=API_TOKEN_VALUE
On the api routes if you have ->middleware('auth:api') Laravel will read the authorization token from the header or using the query parameter and check it to the database value.
Adding the api_token to the user table
If you don't have an api_token field in your user table then add one. It is not the same as remember_token, they are different. So add to your user migration the following:
$table->string('api_token', 60)->unique();
You will need to update the users api_token using something like the following:
$user = User::find(1);
$user->update(['api_token' => str_random(60)]);
That 60 character string you will use where I put VALUE_OF_TOKEN_FROM_DB

Firebase Database query for http trigger

I'm trying to query my firebase realtime database for the list of User objects. I have a favourites field and in it I'm storing a list of id's of favourited users. How would I go about writing a http endpoint with cloud functions so that it returns a json list of User objects corresponding to these ids in database?
Thanks a lot.
You can configure your development environment for FCF by following this. Once you've initialized your project, write a function inside functions/index.js like this one:
exports.getFavouriteUsers = functions.https.onRequest((req, res) => {
var favouriteUsers = admin.database.ref('users/favourites').val();
res.status(200).send(favouriteUsers);
});
Finally deploy and you'll be able to make requests to the endpoint shown in the console.
Look at this documentation for HTTP triggers

Is Firebase storage URL static?

I have a list of contacts and each of those has a profile photo which is stored in Firebase storage. An official way of getting the images would be to fetch the URL using the Firebase storage SDK and set it as src in img element.
firebaseApp.storage().ref("profilePhotos/" + officeId + ".jpg").getDownloadURL().then(function (url) {
this.photoUrl = url;
}.bind(this)).catch(function (error) {
console.log("Photo error"); // TODO: handler
});
This is quite cumbersome when I have to load multiple files (as in contact list). Is the file URL received above static? Can I store it in the database in the profile information and use it directly?
Thanks
A very common pattern is to store the download URL of a file in Realtime Database for easy use later on. Download URLs should work until you choose to revoke them.
In my experience, the download urls are static. Also if you look at the entry in the database below the download url you can see an option to recreate the download url.
Storing the download url in the Realtime Database is a great way to keep track of those download urls. I would use the push method to hold it in a folder in the database.
The way they use .push in the Realtime Database docs example will create a pattern of storage and retrieval that should solve your problem.
.push for making and entry, chained with .key for retrieval later:
var newPostKey = firebase.database().ref().child('posts').push().key;
.once for reading the data at the reference you want with a .then
firebase.database().ref('/users/' + userId).once('value').then(...)

Twilio: Where do the params from Twilio.Device.connect() get sent to

The Twilio JS library has a function called Twilio.Device.connect() which takes params. In the documentation it says these params get sent to the server, but it never specifies which server endpoint it goes to or how to set this up. https://www.twilio.com/docs/client/device
Can anybody explain?
Twilio evangelist here.
The parameters get converted into form encoded values and included in the HTTP request that is made to the URL configured for your TwiML App.
So for example, if you include parameters like this:
params = {"PhoneNumber": "+15555555555"};
Twilio.Device.connect(params);
they will get converted into this set of form encoded values and included in the POST request Twilio makes to your Twiml Apps Voice URL:
PhoneNumber=+15555555555
You can use whatever mechanism in your server side framework that exposes form values to grab those parameters and use them to generate and return TwiML. For example, in PHP:
$phoneNumber = $_REQUEST["PhoneNumber"];
Hope that helps.
Twilio provide web-hook for different events like when call initiated, ringing, completed etc, so you can get your custom parameter from web-hook ,
For Example Lets suppose you want channelId in server side, so First create one GET/POST API and assign to statusCallback url like in TwiML Bin
<Client
statusCallbackEvent='initiated ringing answered completed'
statusCallbackMethod= "GET" statusCallback="https://{{SERVER_ENDPOINT}}/twilio/peer-to-peer-call/{{channelId}}" >
{{To}}
</Client>
Now you can retrieve channelId as request params or request query in your server

Categories

Resources