I use angular 6 , firebase realtime database and angularfire.
I can filter content from my realtime firebase database. However, I did manage to make it work by the function "starts with".
How can I modify my code to obtain a "querytext"?
Thank you for your help
Service.ts
getGeo(queryText:string) {return this.database.list('/EG', ref => ref
.orderByChild("nom")
.startAt(queryText)
.endAt(queryText+"\uf8ff")).snapshotChanges().pipe(map(actions => {
return actions.map(a => {
const data = a.payload.val();
const key = a.payload.key;
return {key, ...data };
});
})); }
Related
I am trying to add pagination to my Zapier trigger.
The API I am using for the trigger supports pagination, but not using a page number in the traditional sense (ie. page 1,2,3,...). Instead, the API response includes a key (ie. "q1w2e3r4") which should be passed as a parameter to the next request to get the next page of results.
From looking at the docs, I can use {{bundle.meta.page}} (which defaults to 0 unless otherwise set).
I am trying to set {{bundle.meta.page}} in the code editor, with an example shown below:
const options = {
url: 'company_xyz.com/api/widgets',
method: 'GET',
...,
params: {
...,
'pagination_key': bundle.meta.page,
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const json_response = response.json;
widgets = json_response.widgets
...
bundle.meta.page = json_response["next_pagination_key"]
return widgets;
});
The problem is that when Zapier tries to retrieve the next page, bundle.meta.page will be 1 instead of the value of "next_pagination_key" from the result of the previous request.
There are docs on cursor-based pagination in the CLI docs.
The relevant block is:
const performWithAsync = async (z, bundle) => {
let cursor;
if (bundle.meta.page) {
cursor = await z.cursor.get(); // string | null
}
const response = await z.request(
'https://5ae7ad3547436a00143e104d.mockapi.io/api/recipes',
{
// if cursor is null, it's sent as an empty query
// param and should be ignored by the server
params: { cursor: cursor }
}
);
// we successfully got page 1, should store the cursor in case the user wants page 2
await z.cursor.set(response.nextPage);
return response.items;
};
This should work in the Zapier Visual Builder, but you might need to use the CLI instead. You can export your integration using the zapier convert CLI command (docs).
Google Sheets document can contain some sheets. First is default and '0'. Generally for any sheet there is address like this:
https://docs.google.com/spreadsheets/d/(spreadsheetId)/edit#gid=(sheetId)
with both spreadsheetId and sheetId.
But in API documentation there is no mention of how to use sheetId. I can only read and edit default sheet for given spreadsheetId.
If in request from code presented in exemplary link I added sheetId property I got error:
{
message: 'Invalid JSON payload received. Unknown name "sheetId": Cannot bind query parameter. Field \'sheetId\' could not be found in request message.',
domain: 'global',
reason: 'badRequest'
}
How to get access to other sheets than default in Google Sheets API and read or update fields in them?
Sheet name is the easiest way to access a specific sheet. As written here, range parameter can include sheet names like,
Sheet1!A1
If you must use a sheet id instead of sheet name, You can use any of the alternate end points which uses dataFilter, like spreadsheets.values.batchUpdateByDataFilter instead of spreadsheets.values.batchUpdate. You can then use sheetId in request body at data.dataFilter.gridRange.sheetId. An example of using such a filter with sheetId is provided by another answer here by ztrat4dkyle.
However, developer metadata is the preferred method of permanently associating objects(sheets/ranges/columns) to variables, where user modifications are expected on such objects.
Essentially we need to use dataFilters to target a specific sheet by ID.
#TheMaster pointed me in the right direction but I found the answers confusing so I just want to share my working example for Node.js.
Here's how to get the value of cell B2 from a sheet that has ID 0123456789
const getValueFromCellB2 = async () => {
const SPREADSHEET_ID = 'INSERT_SPREADSHEET_ID';
const SHEET_ID = 0123456789;
// TODO: replace above values with real IDs.
const google = await googleConnection();
const sheetData = await google.spreadsheets.values
.batchGetByDataFilter({
spreadsheetId: SPREADSHEET_ID,
resource: {
dataFilters: [
{
gridRange: {
sheetId: SHEET_ID,
startRowIndex: 1,
endRowIndex: 2,
startColumnIndex: 1,
endColumnIndex: 2,
},
},
],
},
})
.then((res) => res.data.valueRanges[0].valueRange.values);
return sheetData[0][0];
}
// There are many ways to auth with Google... Here's one:
const googleConnection = async () => {
const auth = await google.auth.getClient({
keyFilename: path.join(__dirname, '../../secrets.json'),
scopes: 'https://www.googleapis.com/auth/spreadsheets',
});
return google.sheets({version: 'v4', auth});
}
To simply read data we're using batchGetByDataFilter where dataFilters is an array of separate filter objects. The gridRange filter (one of many) allows us to specify a sheetId and range of cells to return.
Here is my working example for "rename sheet in spreadsheet by sheetId" function.
You can use other methods from Google Spreadsheets API Docs in the same way. Hope it will be helpful for somebody
<?php
function getClient() //standard auth function for google sheets API
{
$clientConfigPath = __DIR__ . '/google_credentials/client_secret.json';
$client = new Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAuthConfig($clientConfigPath);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = (__DIR__ . '/google_credentials/credentials.json');
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Store the credentials to disk.
if (!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
function renameSheet(string $sheetId, string $newTitle, string $spreadsheetId)
{
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);
$requests = [
new Google_Service_Sheets_Request([
'updateSheetProperties' => [
'properties' => [
'sheetId' => $sheetId,
'title' => $newTitle,
],
'fields' => 'title'
]
])
];
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
'requests' => $requests
]);
return $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest);
}
UPDATE
If you want to get sheet title by sheetId, you can use following function
function getSpreadsheetInfo($spreadsheetId)
{
$client = getClient();
$service = new Google_Service_Sheets($client);
$response = $service->spreadsheets->get($spreadsheetId);
return $response;
}
function getSheets($spreadsheetId)
{
$spreadsheet_info = getSpreadsheetInfo($spreadsheetId);
$sheets_info = [];
foreach ($spreadsheet_info as $item) {
$sheet_id = $item['properties']['sheetId'];
$sheet_title = $item['properties']['title'];
$sheets_info[$sheet_id] = $sheet_title;
}
return $sheets_info;
}
$sheets_info_array = getSheets($YOUR_SPREADSHEET_ID_HERE);
$sheets_info_array will be equal
array (
"sheet_id1(int)" => 'sheet_title1',
"sheet_id2(int)" => 'sheet_title3',
)
so you can get $your_sheet_id's title as $sheets_info_array[$your_sheet_id]
The initial blank empty tab that is always present when a new Google Sheet is created always has sheetId 0 assigned to it.
Subsequently created sheetIds are randomized ten digit numbers. Only the first tab has sheetId 0. Even if you rename a sheet, it's ID remains constant. IDs are never reused - they remain unique within a given sheet.
Using the Google Drive API, access to a Google Sheet is instantiated using the sheet's Google Drive file ID.
Once you have instantiated access to the particular Google Sheet file, you can then reference each tab within the sheet tab and manipulate information, format, etc within a tab of the sheet, by using the 'sheetId' nomenclature.
Here is a PHP example of renaming a Google Sheet's tab name using sheetId 0.
<?php
/*
* Google Sheets API V4 / Drive API V3, rename existing sheet tab example
*
*/
$fileID = '/* pass your Google Sheet Google Drive file ID here */';
$client = new Google_Client();
$client->useApplicationDefaultCredentials(); // the JSON service account key location as defined in $_SERVER
$client->setApplicationName('API Name');
$client->addScope(Google_Service_Drive::DRIVE);
$client->setAccessType('offline');
$client->setSubject('API Instance Subject');
$sheet = new Google_Service_Sheets($client);
$sheetList = $sheet->spreadsheets->get($fileID);
/*
* iterate through all Google Sheet tabs in this sheet
*/
$homeFlag = FALSE;
foreach($sheetList->getSheets() as $sheetRecord) {
/*
* if match, save $sheetTabID from Google Sheet tab
*/
if ($sheetRecord['properties']['sheetId'] == 0) {
$sheetTabID = $sheetRecord['properties']['sheetId'];
$sheetTabTitle = $sheetRecord['properties']['title'];
$homeFlag = TRUE;
}
}
/*
* if $homeFlag is TRUE, you found your desired tab, so rename tab in Google Sheet
*/
if ($homeFlag) {
$newTabName = 'NotTabZero';
$sheetRenameTab = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array('requests' => array('updateSheetProperties' => array('properties' => array('sheetId' => $sheetTabID, 'title' => $newTabName), 'fields' => 'title'))));
$sheetResult = $sheet->spreadsheets->batchUpdate($sheetID,$sheetRenameTab);
}
?>
More simplier answer is to use the A1 Notation to get what sheet and rows you want
const res = await sheets.spreadsheets.values.get({
spreadsheetId: "placeholder_id_value",
range: "Sheet2!A:A", # This will grab all data out of sheet 2 from column A
})
reference
I wanted to trigger a Jenkins job through the Jenkins API
we can do that by hitting the URL similar to "JENKINS_URL/job/JOBNAME/build"
I want to hit the API via Google action/Dialogflow.
Is there any tutorial available to do a similar process that I want to achieve?
You should take a look at the Dialogflow quotes sample, which shows how to make external API calls:
// Retrieve data from the external API.
app.intent('Default Welcome Intent', (conv) => {
// Note: Moving this fetch call outside of the app intent callback will
// cause it to become a global var (i.e. it's value will be cached across
// function executions).
return fetch(URL)
.then((response) => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
} else {
return response.json();
}
})
.then((json) => {
// Grab random quote data from JSON.
const data = json.data[Math.floor(Math.random() * json.data.length)];
const randomQuote =
data.quotes[Math.floor(Math.random() * data.quotes.length)];
conv.close(new SimpleResponse({
text: json.info,
speech: `${data.author}, from Google ` +
`Developer Relations once said... ${randomQuote}`,
}));
if (conv.screen) {
conv.close(new BasicCard({
text: randomQuote,
title: `${data.author} once said...`,
image: new Image({
url: BACKGROUND_IMAGE,
alt: 'DevRel Quote',
}),
}));
}
});
});
I Created a android app in which if a press a button and value changes in Firebase database (0/1) , i want to do this using google assistant, please help me out, i searched out but didn't found any relevant guide please help me out
The code to do this is fairly straightforward - in your webhook fulfillment you'll need a Firebase database object, which I call fbdb below. In your Intent handler, you'll get a reference to the location you want to change and make the change.
In Javascript, this might look something like this:
app.intent('value.update', conv => {
var newValue = conv.prameters.value;
var ref = fbdb.ref('path/to/value');
return ref.set(newValue)
.then(result => {
return conv.ask(`Ok, I've set it to ${newValue}, what do you want to do now?`);
})
.catch(err => {
console.error( err );
return conv.close('I had a problem with the database. Try again later.');
});
return
});
The real problem you have is what user you want to use to do the update. You can do this with an admin-level connection, which can give you broad access beyond what your security rules allow. Consult the authentication guides and be careful.
I am actually working on a project using Dialogflow webhook and integrated Firebase database. To make this posible you have to use the fulfilment on JSON format ( you cant call firebasedatabase in the way you are doing)
Here is an example to call firebase database and display a simple text on a function.
First you have to take the variable from the json.. its something loike this (on my case, it depends on your Entity Name, in my case it was "tema")
var concepto = request.body.queryResult.parameters.tema;
and then in your function:
'Sample': () => {
db.child(variable).child("DESCRIP").once('value', snap => {
var descript = snap.val(); //firebasedata
let responseToUser = {
"fulfillmentMessages": [
{ //RESPONSE FOR WEB PLATFORM===================================
'platform': 'PLATFORM_UNSPECIFIED',
"text": {
"text": [
"Esta es una respuesta por escritura de PLATFORM_UNSPECIFIED" + descript;
]
},
}
]
}
sendResponse(responseToUser); // Send simple response to user
});
},
these are links to format your json:
Para formatear JSON:
A) https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/Shared.Types/Platform
B) https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/Shared.Types/Message#Text
And finally this is a sample that helped a lot!!
https://www.youtube.com/watch?v=FuKPQJoHJ_g
Nice day!
after searching out i find guide which can help on this :
we need to first create chat bot on dialogflow/ api.pi
Then need to train our bot and need to use webhook as fullfillment in
response.
Now we need to setup firebase-tools for sending reply and doing
changes in firebase database.
At last we need to integrate dialogflow with google assistant using google-actions
Here is my sample code i used :
`var admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
var database = admin.database();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.hello = functions.https.onRequest((request, response) => {
let params = request.body.result.parameters;
database.ref().set(params);
response.send({
speech: "Light controlled successfully"
});
});`
I have deployed a cloud function to my Firebase In order to use Firebase as my backend server to handle Stripe payment.
The link of the sample Firebase cloud functions i have used: https://github.com/firebase/functions-samples/tree/master/stripe
Here is the function I should trigger when I charge the user in my app
exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/charges/{id}').onWrite((event) => {
const val = event.data.val();
if (val === null || val.id || val.error) return null;
return admin.database().ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then((snapshot) => {
return snapshot.val();
}).then((customer) => {
const amount = val.amount;
const idempotency_key = event.params.id;
let charge = {amount, currency, customer};
if (val.source !== null) charge.source = val.source;
return stripe.charges.create(charge, {idempotency_key});
}).then((response) => {
return event.data.adminRef.set(response);
}).catch((error) => {
return event.data.adminRef.child('error').set(userFacingMessage(error));
}).then(() => {
return reportError(error, {user: event.params.userId});
});
});
I know that the above function will be triggered when my database changed.
My question is, what is the proper way to pass the Stripe payment detail to my Firebase Database? I am not sure what should I pass to my firebase database after reading the stripe document.
Could anyone help me with this question? Thanks!!
P.S. My developing environment: Objective C, IOS application.
The easiest way is to have your app make an HTTP POST request to an HTTP Firebase function. Your app should already be doing this in order to create the Stripe ephemeral key and you can handle payments in a similar way. After the charge is successful you can save the resulting info to your database.
The function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const bodyParser = require('body-parser');
const stripeApp = express();
stripeApp.use(bodyParser.json());
stripeApp.post('/order', (req, res) => {
const { source } = req.body; // This is the token provided by your app
return stripe.charges.create({...}) // the actual payment
});
exports.stripeAPI = functions.https.onRequest(stripeApp);
Have a took at Stripe's demo iOS app - its swift but it should still make sense in Obj-C world. https://github.com/stripe/stripe-connect-rocketrides/tree/master/ios/RocketRides.
Particularly https://github.com/stripe/stripe-connect-rocketrides/blob/master/ios/RocketRides/MainAPIClient.swift#L39
So the process that works for me is -
1) iOS provides card details to Stripe using native SDK
2) Stripe provides a token which you send it to your Firebase backend
you could store it in stripeTokens/userId/yourToken
3) Firebase cloud function then triggers a function and uses this token to create Stripe customer (See saving for later and Customer)
you could store it in stripe_customers/userId/stripeCustomerId like your example
4) Remember to remove yourToken because it's only valid once
5) finally you can use this stripeCustomerId to make payments
Important concept here is to create a customer and store in your backend for future payments.
Hope this helps.