Nicolas Garnier
9 years ago
3 changed files with 97 additions and 7 deletions
@ -0,0 +1,58 @@ |
|||
# Tracking last modified Date of a Firebase Database |
|||
|
|||
This template shows how to keep track of the date at which the Firebase Database or a subset of a firebase Database was last modified. |
|||
|
|||
## Cloud Function Code |
|||
|
|||
See file [index.js](index.js) for the code. |
|||
|
|||
This is done by simply updating a `lastmodified` attribute on the parent of the node which is tracked (for instance at the root of the Database). |
|||
|
|||
## Sample Database Structure |
|||
|
|||
As an example we'll be using a simple chat database structure: |
|||
|
|||
``` |
|||
/functions-project-12345 |
|||
/chat |
|||
/key-123456 |
|||
username: "Mat" |
|||
text: "Hey Bob!" |
|||
/key-123457 |
|||
username: "Bob" |
|||
text: "Hey Mat" |
|||
``` |
|||
|
|||
## Trigger rules |
|||
|
|||
Below is the trigger rule for the `touch` function making sure it's triggered when a new chat message is added/modified. |
|||
|
|||
``` |
|||
"functions": { |
|||
".source": "functions", |
|||
"touch": { |
|||
"triggers": { |
|||
"database": { |
|||
"path": "/chat/$message", |
|||
} |
|||
} |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Security Rules |
|||
|
|||
The following security rules ensures only a Cloud Function with admin access can update the `lastmodified` attribute. |
|||
|
|||
``` |
|||
{ |
|||
"rules": { |
|||
"lastmodified": { |
|||
".write": "false", // TODO: Check taht this works with GCF admin access! |
|||
".read": "true" |
|||
} |
|||
} |
|||
} |
|||
``` |
|||
|
|||
|
@ -0,0 +1,36 @@ |
|||
/** |
|||
* Copyright 2015 Google Inc. All Rights Reserved. |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* 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. |
|||
*/ |
|||
'use strict'; |
|||
|
|||
var Firebase = require('firebase'); |
|||
var env = require('./env'); |
|||
var ref = new Firebase(env.get('firebase.database.url')); |
|||
|
|||
function touch(context, data) { |
|||
ref.auth(env.get('firebase.database.token'), function(error, result) { |
|||
if (error) { |
|||
context.done(error); |
|||
} else { |
|||
console.log('Authenticated successfully with admin rights'); |
|||
ref.child('lastmodified').set(Firebase.ServerValue.TIMESTAMP); |
|||
context.done(); |
|||
} |
|||
}); |
|||
} |
|||
|
|||
module.exports = { |
|||
touch: touch |
|||
} |
Loading…
Reference in new issue