Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new readme #1

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
"extends": "airbnb-base",
};
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
node_modules
private_key.json
private_key.json
secret
config/test.js
app.js
62 changes: 51 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,63 @@ npm install
```

## 準備 Google Calendar Api 服務帳戶金鑰
將 ```private_key.json``` 放置於專案目錄
1. 新增專案
2. 前往[API和服務](https://console.cloud.google.com/apis/credentials)

![API和服務](images/1.png)

3. 建立服務帳戶金鑰

![API和服務](images/2.png)

4. 將私密金鑰存至電腦中
![API和服務](images/3.png)


## 範例
將上一步金鑰內 ```client_email``` 與 ```private_key``` 複製到 default.js 中

./config/default.js
```js
module.exports = {
CLIENT_EMAIL: 'your client email',
PRIVATE_KEY: 'your private key'
};
```
let gCalHelper = new GCalHelper();

gCalHelper.listEvents(
moment().startOf('month'), // start(default: start of month)
moment().endOf('month'), // end(default: end of month)
function(events) { // callback function
// got events
}
);
app.js
```js
const config = require('./config/default');

let gCalHelper = new GCalHelper({
CLIENT_EMAIL: config.CLIENT_EMAIL,
PRIVATE_KEY: config.PRIVATE_KEY
});

gCalHelper.listEvents({
start: '2018-01-01',
end: '2018-01-31'
}).then(function(events){
// handle events...
}).catch(function(err){
// handle error...
});
```

## API

### listEvents(params)
回傳:[Events Resouce](https://developers.google.com/google-apps/calendar/v3/reference/events#resource)

參數:

|名稱|型態|
|-|-|
|`start`|`string` / `dateTime`|
|`end`|`string` / `dateTime`|


## 測試
使用 `npm test` 測試

## License
MIT
MIT
90 changes: 58 additions & 32 deletions __tests__/index.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,68 @@
var GCalHelper = require("./../index");
var moment = require("moment");
const GCalHelper = require('./../index');
const config = require('../config/test.js');

let gcalHelper = new GCalHelper();
const gCalHelper = new GCalHelper({
CLIENT_EMAIL: config.CLIENT_EMAIL,
PRIVATE_KEY: config.PRIVATE_KEY,
});

const event = {
summary: 'Google I/O 2015',
location: '800 Howard St., San Francisco, CA 94103',
description: 'A chance to hear more about Google\'s developer products.',
start: {
dateTime: '2015-05-28T09:00:00-07:00',
timeZone: 'America/Los_Angeles',
},
end: {
dateTime: '2015-05-28T17:00:00-07:00',
timeZone: 'America/Los_Angeles',
},
recurrence: [
'RRULE:FREQ=DAILY;COUNT=2',
],
attendees: [
{ email: '[email protected]' },
{ email: '[email protected]' },
],
reminders: {
useDefault: false,
overrides: [
{ method: 'email', minutes: 24 * 60 },
{ method: 'popup', minutes: 10 },
],
},
};

test("Got start and end", () => {
gcalHelper.listEvents(
moment([2018, 0, 26, 0, 0, 0]),
moment([2018, 0, 26, 23, 59, 59])
);
test('Events: insert [Got an event]', async () => {
await gCalHelper.addEvents(event)
.then((res) => {
expect(res).toMatchObject(event);
});
});

test("Got start", () => {
gcalHelper.listEvents(
moment([2018, 0, 26, 0, 0, 0])
);
test('Events: list [Got start and end]', async () => {
await gCalHelper
.listEvents({
start: '2015-05-01',
end: '2015-05-31',
});
});

test("Got end", () => {
gcalHelper.listEvents(
undefined,
moment([2018, 0, 26, 23, 59, 59])
);
test('Events: list [Got start]', async () => {
await gCalHelper
.listEvents({
start: '2015-05-01',
});
});

test("Miss both", () => {
gcalHelper.listEvents();
test('Events: list [Got end]', async () => {
await gCalHelper
.listEvents({
end: '2015-05-31',
});
});

// gcalHelper.addEvents({
// start: {
// dateTime: moment()
// .add(4, "h")
// .format()
// },
// end: {
// dateTime: moment()
// .add(5, "h")
// .format()
// },
// summary: "Dinner"
// });
test('Events: list [Miss both]', async () => {
await gCalHelper.listEvents();
});
4 changes: 4 additions & 0 deletions config/default.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
CLIENT_EMAIL: '',
PRIVATE_KEY: '',
};
Binary file added images/1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
130 changes: 64 additions & 66 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,74 +1,72 @@
var fs = require("fs");
var moment = require("moment");
var google = require("googleapis");
var googleAuth = require("google-auth-library");
var privatekey = require("./private_key.json");
const moment = require('moment');
const google = require('googleapis');

const calendar = google.calendar('v3');

class GCalHelper {
constructor() {
this.jwtClient = new google.auth.JWT(
privatekey.client_email,
null,
privatekey.private_key,
["https://www.googleapis.com/auth/calendar"]
);
//authenticate request
this.jwtClient.authorize(function(err, tokens) {
if (err) {
console.log(err);
return;
} else {
// console.log("Successfully connected!");
}
});
}
constructor({ CLIENT_EMAIL, PRIVATE_KEY }) {
this.jwtClient = new google.auth.JWT(
CLIENT_EMAIL,
null,
PRIVATE_KEY,
['https://www.googleapis.com/auth/calendar'],
);
this.jwtClient.authorize((err, tokens) => {
if (err) {
return new Error(err);
}
return tokens;
});
}

addEvents(event, callback) {
let calendar = google.calendar("v3");
calendar.events.insert(
{
auth: this.jwtClient,
calendarId: "primary",
resource: event
},
function(err, response) {
if (err) {
console.log("The API returned an error: " + err);
return;
}
callback(response);
}
);
}
async addEvents(resource) {
return new Promise((resolve, reject) => {
calendar.events.insert({
auth: this.jwtClient,
calendarId: 'primary',
resource,
}, (err, response) => {
if (err) {
reject(new Error(`Error occured while adding event: ${err}`));
}
resolve(response.data);
});
});
}

/**
* Return list of events between given search range.
*
* @param {Date} start Start of search range.
* @param {Date} end End of search range.
* @param {Function} callback Callback function.
*/
listEvents(start, end, callback) {
if (typeof start === "undefined") start = moment().startOf("month");
if (typeof end === "undefined") end = moment().endOf("month");
async deleteEvent(eventId) {
return new Promise((resolve, reject) => {
calendar.events.delete({
auth: this.jwtClient,
calendarId: 'primary',
eventId,
}, (err, response) => {
if (err) {
reject(new Error(`Error occured while deleting event: ${err}`));
}
resolve(response);
});
});
}

let calendar = google.calendar("v3");
calendar.events.list(
{
auth: this.jwtClient,
calendarId: "primary",
timeMin: moment(start).toDate(),
timeMax: moment(end).toDate()
},
function(err, response) {
if (err) {
console.log("The API returned an error: " + err);
}
var events = response.data.items;
if (typeof callback === "function") callback(events);
}
);
}
async listEvents({
start = moment().startOf('month'),
end = moment().endOf('month'),
} = {}) {
return new Promise((resolve, reject) => {
calendar.events.list({
auth: this.jwtClient,
calendarId: 'primary',
timeMin: moment(start).toDate(),
timeMax: moment(end).toDate(),
}, (err, response) => {
if (err) {
reject(new Error(`Error occured while show event: ${err}`));
}
resolve(response.data.items);
});
});
}
}

module.exports = GCalHelper;
Loading