Need good example: Google Calendar API in Javascript - google-calendar-api

What I'm trying to do:
Add events to a google calendar from my site using javascript.
What I can't do:
Find a good tutorial/walk through/example for the google calendar api. All the documentation I've been able to find links back and forth between v1 and v2 api's, or the v3 api doesn't seem to be client based.
For those that are curious, the site I'm developing this for:
http://infohost.nmt.edu/~bbean/banweb/index.php

Google provides a great JS client library that works with all of Google's discovery-based APIs (such as Calendar API v3). I've written a blog post that covers the basics of setting up the JS client and authorizing a user.
Once you have the basic client enabled in your application, you'll need to get familiar with the specifics of Calendar v3 to write your application. I suggest two things:
The APIs Explorer will show you which calls are available in the API.
The Chrome developer tools' Javascript console will automatically suggest method names when you are manipulating gapi.client. For example, begin typing gapi.client.calendar.events. and you should see a set of possible completions (you'll need the insert method).
Here's an example of what inserting an event into JS would look like:
var resource = {
"summary": "Appointment",
"location": "Somewhere",
"start": {
"dateTime": "2011-12-16T10:00:00.000-07:00"
},
"end": {
"dateTime": "2011-12-16T10:25:00.000-07:00"
}
};
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': resource
});
request.execute(function(resp) {
console.log(resp);
});
Hopefully this is enough to get you started.

this should do the trick
//async function to handle data fetching
async function getData () {
//try catch block to handle promises and errors
try {
const calendarId = ''
const myKey = ''
//using await and fetch together as two standard ES6 client side features to extract the data
let apiCall = await fetch('https://www.googleapis.com/calendar/v3/calendars/' + calendarId+ '/events?key=' + myKey)
//response.json() is a method on the Response object that lets you extract a JSON object from the response
//response.json() returns a promise resolved to a JSON object
let apiResponse = await apiCall.json()
console.log(apiResponse)
} catch (error) {
console.log(error)
}
}
getData()

Related

Using Graph in Outlook addin to read email in MIME format

I am getting lost with Outlook addin development and really need some help.
I have developed an addin that sends selected email to another server via REST API and it worked fine, but there was a limitation to 1MB so I tried to develop a solution that use ewsURL + SOAP but faced with CORS issues.
Now I got a suggestion to use GRAPH approach (fine with me) but I have no idea how that suppose to work using JavaScript.
Basically I need to get an email as MIME/EML format.
I was guided to check this article: https://learn.microsoft.com/en-us/graph/outlook-get-mime-message
There is endpoint that looks promissing:
https://graph.microsoft.com/v1.0/me/messages/4aade2547798441eab5188a7a2436bc1/$value
But I do not see explanation
how to make authorization process?
I have tried to get token from getCallbackTokenAsync but that did not work
I have tried Office.context.auth.getAccessTokenAsync but getting an issue:
Error code: 13000 Error name: API Not Supported.
Error message: The identity API is not supported for this add-in.
how to get email id
I have tried to do Office.context.mailbox.item.itemId but it looks different compare to what I have seen in the examples (but hopefully that is not a problem)
Please help :-)
There are 2 solutions here. It is preferred longer term to use graph end point with https://learn.microsoft.com/en-us/office/dev/add-ins/develop/authorize-to-microsoft-graph and you can use https://graph.microsoft.com/v1.0/me/messages/4aade2547798441eab5188a7a2436bc1/$value. However this solution requires a backend / service . Transferring through backend is preferable for large content so the content can transfer directly from Exchange to the service.
Alternatively, you can get token from getCallbackTokenAsync, from this doc: https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/use-rest-api
As you noted is that you will need to translate the ews id using convertToRestId. Putting together, your solution should look something like this:
Office.context.mailbox.getCallbackTokenAsync({isRest: true}, function(result){
if (result.status === "succeeded") {
let token = result.value;
var ewsItemId = Office.context.mailbox.item.itemId;
const itemId = Office.context.mailbox.convertToRestId(
ewsItemId,
Office.MailboxEnums.RestVersion.v2_0);
// Request the message's attachment info
var getMessageUrl = Office.context.mailbox.restUrl +
'/v2.0/me/messages/' + itemId + '/$value';
var xhr = new XMLHttpRequest();
xhr.open('GET', getMessageUrl);
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.onload = function (e) {
console.log(this.response);
}
xhr.onerror = function (e) {
console.log("error occurred");
}
xhr.send();
}
});

Best way to intercept XHR request on page with Puppeteer and return mock response

I need to be able to intercept XHR requests on page loaded with Puppeteer and return mock responses in order to organize backendless testing for my web app. What's the best way to do this?
It seems that the way to go is request.respond() indeed, but still, I couldn't find a concrete example in the web on how to use it. The way I did it was like this:
// Intercept API response and pass mock data for Puppeteer
await page.setRequestInterception(true);
page.on('request', request => {
if (request.url() === constants.API) {
request.respond({
content: 'application/json',
headers: {"Access-Control-Allow-Origin": "*"},
body: JSON.stringify(constants.biddersMock)
});
}
else {
request.continue();
}
});
What happens here exactly?
Firstly, all requests are intercepted with page.setRequestInterception()
Then, for each request I look for the one I am interested in, by matching it by URL with if (request.url() === constants.API) where constants.API is just the endpoint I need to match.
If found, I pass my own response with request.respond(), otherwise I just let the request continue with request.continue()
Two more points:
constants.biddersMock above is an array
CORS header is important or access to your mock data will not be allowed
Please comment or refer to resources with better example(s).
Well. In the newest puppeteer,it provide the request.respond() method to handle this situation.
If anyone is interested I ended up creating special app build for my testing needs, which adds Pretender to the page. And I communicate with Pretender server using Puppeteer's evaluate method.
This is not ideal, but I couldn't find a way to achieve what I need with Puppeteer only. There is a way to intercept requests with Puppeteer, but seems to be no way to provide fake response for a given request.
UPDATE:
As X Rene mentioned there is now native support for this in Puppeteer v0.13.0 using request.respond() method. I'm going to rewrite my tests to use it instead of Pretender, since this will simplify many things for me.
UPDATE 2:
There is pptr-mock-server available now to accomplish this. Internally it relies on request interception and request.respond() method. Library is pretty minimal, and may not fit your needs, but it at least provides an example how to implement backendless testing using Puppeteer. Disclaimer: I'm an author of it.
I created a library that uses Puppeteer's page.on('request') and page.on('response') to record and respond with mocked requests.
https://github.com/axiomhq/puppeteer-request-intercepter
npm install puppeteer-request-intercepter
const puppeteer = require('puppeteer');
const { initFixtureRouter } = require('puppeteer-request-intercepter');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Intercept and respond with mocked data.
const fixtureRouter = await initFixtureRouter(page, { baseUrl: 'https://news.ycombinator.com' });
fixtureRouter.route('GET', '/y18.gif', 'y18.gif', { contentType: 'image/gif' });
await page.goto('https://news.ycombinator.com', { waitUntil: 'networkidle2' });
await page.pdf({ path: 'hn.pdf', format: 'A4' });
await browser.close();
})();
You may want to try out Mockiavelli - request mocking library for Puppeteer. It was build exactly for backendless testing of webapps. It integrates best with jest and jest-puppeteer, but works with any testing library.

Google Cloud Print or other service to auto print using C# or PHP

Are there ANY code examples of how to use Google Cloud Print (using the new OAuth 2) and how when a document comes into the Google Cloud Print queue to automatically print it?
Pretty much what I am trying to do is not spend thousands of dollars that when an order is submitted to our online store, that the order automatically gets printed to our printer. Any ideas, pointers, code examples.
I have done a bunch of searching, and a lot of examples using C#, use Google's old service, not the OAuth2, documentation.
Pretty much, I need a service that will sent a print command to our printer when we get an order in. I can write the part from the store to the service, it is the service to the printer part I have a ton of trouble with.
Thanks in advance.
There's a brilliant PHP class you can download and use that does exactly that:
https://github.com/yasirsiddiqui/php-google-cloud-print
The problem with what you want to achieve is that Google Cloud Print is meant for authenticated users submitting their own print jobs. If I understand correctly, you want to have the server submit a print job as a callback after receiving an order. Therefore, print jobs need to be submitted by a service account, not a Google user. This can be done (we use it in production at the company I work for) using a little hack, described here:
Share printer with Google API Service Account
I can't help you with C# or PHP code, basically you need to be able to make JWT authenticated calls to Google Cloud Print, here you are a code snippet in NodeJS, hope it helps:
var request = require('google-oauth-jwt').requestWithJWT();
service.submitJob = function(readStream,callback) {
// Build multipart form data
var formData = {
printerid: cloudPrintConfig.googleId,
title: 'My Title',
content: readStream,
contentType: "application/pdf",
tag: 'My tag',
'ticket[version]': '1.0',
'ticket[print]': ''
};
// Submit POST request
request({
uri: cloudPrintConfig.endpoints.submit,
json: true,
method: 'post',
formData: formData,
jwt: cloudPrintConfig.jwt
}, function (err, res, body) {
if (err) {
callback(err,null);
} else {
if (body.success == false) {
callback('unsuccessful submission',null);
} else {
callback(null, body);
}
}
});
}
Details about JWT credentials can be found here

How to call node.js REST API from .NET

If I put the jquery code below within the script tag within a html page and drag the html page into a web browser the call to the API specified in the URL is made and I get back a response in JSON format. So this works good.
The reason I want to use .NET for calling the rest API that is made in node.js is because I want to use the unit test utility that exist in visual studio.
So when I start the unit test the call to the REST API made in node.js should be made and then I can check whatever I want in the returned json format by using the assert.AreEqual.
I have googled a lot and there is several example about
Unit Testing Controllers in ASP.NET Web API 2 but I don't want to unit test controller. I only want to call the REST API(made in node.js) when I start my unit test.
I assume to use .NET in the way I want is probably quite rare.
If it's not possible to use .NET and unit test in the way that I want here
I will use another test framework.
I hope to get some help from here.
Hope you understand what I mean.
$.ajax({
type: 'GET',
url: 'http://10.1.23.168:3000/api/v1/users/1',
dataType: 'json',
async: false,
headers: {
'Authorization': 'Basic ' + btoa('DEFAULT/user:password')
},
success: function(response) {
//your success code
console.log(response);
},
error: function (err) {
//your error code
console.log(err);
}
});
Many thanks
Basically what you need to do is to call node.js' API from your C# test code in a same way you call it using jQuery. There are several ways to do it:
Use HttpWebRequest class https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest%28v=vs.110%29.aspx
Use HttpClient class https://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.118%29.aspx It's more "RESTable" since it exposes methods to call HTTP methods like GET, PUT, POST and DELETE methods directly.
3rd party software http://restsharp.org/
Generally I recommend approach #2.
Here's the example source with all the rest of the code.
Another resource is the docs.
This code snippet should be enough to get you where you need.
using(var client = newHttpClient())
{
client.BaseAddress = newUri("http://localhost:55587/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json"));
//GET Method
HttpResponseMessage response = awaitclient.GetAsync("api/Department/1");
if (response.IsSuccessStatusCode)
{
Departmentdepartment = awaitresponse.Content.ReadAsAsync < Department > ();
Console.WriteLine("Id:{0}\tName:{1}", department.DepartmentId, department.DepartmentName);
Console.WriteLine("No of Employee in Department: {0}", department.Employees.Count);
}
else
{
Console.WriteLine("Internal server Error");
}
}

Express.js get http method in controller

I am building a registration form (passport-local as authentication, forms as form helper).
Because the registration only knows GET and POST I would like to do the whole handling in one function.
With other words I am searching after something like:
exports.register = function(req, res){
if (req.isPost) {
// do form handling
}
res.render('user/registration.html.swig', { form: form.toHTML() });
};
The answer was quite easy
exports.register = function(req, res) {
if (req.method == "POST") {
// do form handling
}
res.render('user/registration.html.swig', { form: form.toHTML() });
};
But I searched a long time for this approach in the express guide.
Finally the node documentation has such detailed information:
http://nodejs.org/api/http.html#http_http_request_options_callback
Now you can use a package in npm => "method-override", which provides a middle-ware layer that overrides the "req.method" property.
Basically your client can send a POST request with a modified "req.method", something like /registration/passportID?_method=PUT.
The
?_method=XXXXX
portion is for the middle-ware to identify that this is an undercover PUT request.
The flow is that the client sends a POST req with data to your server side, and the middle-ware translates the req and run the corresponding "app.put..." route.
I think this is a way of compromise. For more info: method-override

Resources