Proper way to ADD a Restart API with async/await method - rest

Im working on a project that requires me to add a restart Api to the system/settings/restart. What is a proper way of creating it with Asynch/Await method.
As an Example here is a Asynch Get Request:
async getSystemInfo(searchParams={fields: ' '}) Promise <ISystemInfo>{
const url = this.joinUri(this.host, RESTEndpoints.systemInfo, searchParams);
const response =await this.doGET(url);
expect(response.status).equal(200, ' ');
return response.data.items[0];

Related

Flutter Unit test http mock returns 400 when it should return 200

Not really sure what's going on, and every tutorial I find seems to set things up the same way.
Essentially I've mocked out an http.client using Mockito and I'm trying to stub an http get request like so:
test("Return 'has_on_boarded' when firebaseUid is valid", () async {
final client = MockClient();
const uid = "123";
when(client.get(Uri.parse("${dotenv.env['BASE_API_URL']}/users/$uid")))
.thenAnswer((_) async =>
http.Response('{"user":{"has_onboarded":true}}', 200));
expect(await UserRepository().initialize(client, uid), "has_on_boarded");
});
For some reason, I only get 400s and not the 200 or body I'm telling it to return with.
Update:
Here is the Flutter tutorial I'm using.
I did discover that using testwidgetsflutterbinding makes all http requests return 400, though since it is being mocked that seems weird.
I've removed that part, however, while it's no longer erroring http.Response('{"user":{"has_onboarded":true}} still resulting in {"user":{"has_onboarded":true}} being returned...

Flutter async rest api call in synchronised way

I have an API to fetch results based on some user typed text. I want api calls to run in syncronized way so last API call result should be in last.
Use case
User type #cbc
API is calling 4 time
#, #c, #cb and #cbc
Issue is API result is giving result randomly not in syncronized way.
Future<void> getHashtags(String tagName) async {
var params = jsonEncode(
{"tag_name": tagName, "latest_hashtag_community": true});
var response = await _postRepository.getHashTags(params,
pageNo: pageNumberHashtags);
}

POST Data Azure Function

I am using Azure Function as a POST API to post the body to an MongoDB. With the code below
module.exports = async function (context, req) {
await client.connect();
const database = client.db("test");
const collection = database.collection("notes");
await collection.insertOne(req.body)
}
Everything is working in debug mode, I checked with POSTman but once I send the code to deploy on Azure, the post does not work, and I get this html page? I don't understand
Wrong URL endpoint
Thanks Max Ivanov

How to query firestore with the Dialogflow inline editor to get information

I am using the inline editor within Dialogflow with the aim of making queries to the database I have created within Firestore.
In short, the user requests a list of courses, I'd like the chatbot to then grab that information form the db and display that back to the user.
Below I have tried to create a function that will do this, I want to take the user input, say "Art Courses" and have my db return those results.
So far, I have created a function that is triggered when the intent is matched, like so;
function getCourses(agent){
let courseRequest = agent.parameters.courseRequest;
if (getCourses){
console.log('Here is the list you requested for ${getCourses}' + parameters.courseRequest);
return admin.firestore().collection('Course_Information').doc.where('CoureTypes').get();
}
}
Are there any notable things I need to add to my function to perform what I wish to achieve?
Thank you.
UPDATE
This code deploys fine, but when I communicate with my bot and trigger the CourseEnquiry intent, cloud Functions shows this error:
admin.collection is not a function
Whilst this seems self explanatory I can't make sure of what it means, I thought declaring const admin = require('firebase-admin');enables me to use admin.collection
// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function getDate(agent){
var today = new Date();
}
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function test(agent){
agent.add("The test is successful");
}
function getCourses(agent){
// Get the database collection and document
const getCourseDoc = admin.collection('Course_Information').doc('Course_Types');
return getCourseDoc.get()
.then(doc => {
if (!doc.exists) {
agent.add('No data found in the database!');
} else {
agent.add(doc.data().entry);
}
return Promise.resolve('Here is the information you wanted');
}).catch(() => {
agent.add('Error reading entry from the Firestore database.');
});
}
function getSubmissionDateSep(agent){
agent.add('Your next submission date is for coursework 1 is');
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Test_Test', test);
intentMap.set('CourseEnquiry', getCourses);
intentMap.set('Submission_Dates - sept', getSubmissionDateSep);
agent.handleRequest(intentMap);
});
UPDATE #2
Hey guys, still not got anywhere with this, I have tried adding:
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
According to this document but I get this error when deploying:
The deployment of your Cloud Function failed:
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: Error: Firebase config variables are not available. Please use the latest version of the Firebase CLI to deploy this function.
You don't show how you're responding to the user with your results, but you'll want to make sure you handle that as part of the then() clause in a Promise. Since the get() in the firestore collection returns a Promise, and you are returning it from your function, you need to make sure that the calling function treats it as a Promise, has a then() clause, and sends back the result as part of something inside this clause.

How can I access DialogFlow parameters using DialogFlowApp or ActionsSDKApp client library?

I'm using DialogFlow to create a Google Assistant Application. For fullfilment I'm using a custom app with NodeJS client library.
I noted that when DialogFlow's request get my application I can see all request, also the parameters object
const astronomyAssistant = functions.https.onRequest((request, response) => {
const app = new DialogflowApp({ request, response });
console.log(`Request headers: ${JSON.stringify(request.headers)}`);
console.log(`Request body: ${JSON.stringify(request.body)}`);
app.handleRequest(actionMap);
});
There some way to access the request object inside of a handle action? How can I access request object using app?
Workaround:
You can put all handle function that depends of request object inside of functions.https.onRequest callback.
For instance:
const astronomyAssistant = functions.https.onRequest((request, response) => {
const app = new DialogflowApp({ request, response });
console.log(`Request headers: ${JSON.stringify(request.headers)}`);
console.log(`Request body: ${JSON.stringify(request.body)}`);
const foo = app => {
console.log(request);
}
actionMap.set('input.foo', foo);
app.handleRequest(actionMap);
});
But, for sure this is not a good practice.
You can use app.getArgument("my-parameter") to quickly access any parameter you've defined within your actions.