Skip to content

Base features #1

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

Merged
merged 7 commits into from
Mar 14, 2019
Merged
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
75 changes: 75 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
version: 2.1

orbs:
codecov: codecov/codecov@1.0.4
build-helpers: style/build-helpers@1.3.1

references:
attach_workspace: &attach_workspace
attach_workspace:
at: ~/repo
persist_to_workspace: &persist_to_workspace
persist_to_workspace:
root: ~/repo
paths: .

executors:
albus:
docker:
- image: circleci/node:10.15.1
working_directory: ~/repo

jobs:
install_dependencies:
executor: albus
steps:
- *attach_workspace
- checkout
- restore_cache:
keys:
- v1-dependencies-{{ checksum "package.json" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
- run: npm install
- save_cache:
paths:
- node_modules
key: v1-dependencies-{{ checksum "package.json" }}
- *persist_to_workspace
test:
executor: albus
steps:
- *attach_workspace
- run: npm test
- codecov/upload:
file: .nyc_output/*.json
- *persist_to_workspace
publish:
executor: albus
steps:
- *attach_workspace
- checkout
- run: npx semantic-release

workflows:
build:
jobs:
- install_dependencies:
context: pi
filters:
branches:
only: /.*/
- test:
context: pi
requires:
- install_dependencies
filters:
branches:
only: /.*/
- publish:
context: pi
requires:
- test
filters:
branches:
only: master
3 changes: 3 additions & 0 deletions .sgcrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{

}
34 changes: 34 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@

{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Mocha All",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"--timeout",
"999999",
"--colors",
"'${workspaceFolder}/{,!(node_modules)/}*/*.test.js'"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"type": "node",
"request": "launch",
"name": "Mocha Current File",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"--timeout",
"999999",
"--colors",
"${file}"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}
76 changes: 76 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at pi-team@smartthings.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
4 changes: 2 additions & 2 deletions LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright [yyyy] [name of copyright owner]
Copyright 2019 SmartThings, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand All @@ -198,4 +198,4 @@
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
limitations under the License.
86 changes: 85 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,86 @@
# firestore-context-store-nodejs
Stores SmartApp configuration and auth tokens for use in app-initiated calls

<p>
<a href="https://npmjs.org/package/@smartthings/firestore-context-store"><img src="https://badge.fury.io/js/@smartthings/firestore-context-store.svg"></a>
<a href="https://circleci.com/gh/SmartThingsCommunity/firestore-context-store-nodejs.svg?style=svg"><img src="https://circleci.com/gh/SmartThingsCommunity/firestore-context-store-nodejs.svg?style=svg"></a>
<a href="https://david-dm.org/SmartThingsCommunity/firestore-context-store-nodejs"><img src="https://david-dm.org/SmartThingsCommunity/firestore-context-store-nodejs.svg?theme=shields.io"></a>
<a href="https://codecov.io/gh/SmartThingsCommunity/firestore-context-store-nodejs"><img src="https://codecov.io/gh/SmartThingsCommunity/firestore-context-store-nodejs/branch/master/graph/badge.svg" /></a>
</p>

> Stores SmartApp configuration and auth tokens for use in app-initiated calls

Used by the [SmartApp SDK](https://github.com/SmartThingsCommunity/smartapp-sdk-nodejs) to store IDs and access tokens for an installed instance of a SmartApp
and retrieves that information for use in asynchronous API calls. The use of a context store
is only needed when SmartApps have to call the SmartThings API in response to external
events. SmartApps that only response to lifecycle events from the SmartThings platform
will automatically have the proper context without the app having to store it.

The context stored by this module consists of the following data elements:

- **installedAppId**: the UUID of the installed app instance. This is the primary key of the table.
- **locationId**: the UUID of the location in which the app is installed
- **authToken**: the access token used in calling the API
- **refreshToken**: the refresh token used in generating a new access token when one expires
- **clientId**: the SmartApp's client ID, used in generating a new access token
- **clientSecret**: the SmartApp's client secret, used in generating a new access token
- **config**: the current installed app instance configuration, i.e. selected devices, options, etc.v

## Installation

```shell
npm install @smartthings/firestore-context-store --save
```

## Usage

### A note about usage

This package currently targets initializing Cloud Firestore from your own server by using a Service Account. If you are hosted on something like [Firebase Cloud Functions](https://firebase.google.com/docs/functions/) or [Google Cloud Platform](https://cloud.google.com/), we don't currently support those methodologies – feel free to contribute!

To use this module to add Firebase Cloud Firestore context storage to your SmartApp, you should:

1. **Generate a service account**. We use the Firebase Admin SDK. Go to IAM & admin > Service accounts in the Cloud Platform Console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK in the next step.

1. **`require()` your Google Services service account JSON file.** Be certain that you don't ever commit this file to a public repository.

1. **Create a context store instance** with the service account object and the document collection name and pass it to the SmartApp SDK object. For example, the following code:

```javascript
const smartapp = require('@smartthings/smartapp');
const FirestoreDBContextStore = require('@smartthings/firestore-context-store');
const serviceAccount = require('./googleservices-YOURAPPNAME-AND-ID.json')

smartapp
.contextStore(new FirestoreDBContextStore(serviceAccount, 'installedapps'))
.configureI18n()
.page('mainPage', (page) => {
...
```

This will use a document collection named `installedapps` to store documents as keyed by the `installedAppId` value.

### Firebase Console

From the Firebase Cloud Firestore console, you will see a new document collection with persisted contexts.

![img](docs/example_console.png)

## More about SmartThings

If you are not familiar with SmartThings, we have
[extensive on-line documentation](https://smartthings.developer.samsung.com/develop/index.html).

To create and manage your services and devices on SmartThings, create an account in the
[developer workspace](https://devworkspace.developer.samsung.com/).

The [SmartThings Community](https://community.smartthings.com/c/developers/) is a good place share and
ask questions.

There is also a [SmartThings reddit community](https://www.reddit.com/r/SmartThings/) where you
can read and share information.

## License and Copyright

Licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0)

Copyright 2019 SmartThings, Inc.
8 changes: 8 additions & 0 deletions config/release.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
analyzeCommits: {
preset: 'eslint'
},
generateNotes: {
preset: 'eslint'
}
}
Binary file added docs/example_console.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
62 changes: 62 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
'use strict'

const admin = require('firebase-admin')

module.exports = class FirestoreDBContextStore {
constructor(serviceAccount, collectionName) {
if (!serviceAccount) {
throw new Error('Need a valid serviceAccount.json')
}

this.serviceAccount = serviceAccount
this.collectionName = collectionName || 'installedApps'

admin.initializeApp({
credential: admin.credential.cert(this.serviceAccount)
})
this.db = admin.firestore()
this.installedApps = this.db.collection(this.collectionName)
}

get(installedAppId) {
return new Promise((resolve, reject) => {
this.installedApps
.doc(installedAppId)
.get()
.then(snapshot => {
resolve(snapshot.data())
})
.catch(reject)
})
}

put(params) {
return new Promise((resolve, reject) => {
this.installedApps
.doc(params.installedAppId)
.set(params, {merge: true})
.then(resolve)
.catch(reject)
})
}

update(installedAppId, params) {
return new Promise((resolve, reject) => {
this.installedApps
.doc(installedAppId)
.update(params, {merge: true})
.then(resolve)
.catch(reject)
})
}

delete(installedAppId) {
return new Promise((resolve, reject) => {
this.installedApps
.doc(installedAppId)
.delete()
.then(resolve)
.catch(reject)
})
}
}
Loading