Skip to content

Instantly share code, notes, and snippets.

@Fleker
Created April 30, 2019 00:35
Show Gist options
  • Save Fleker/5d590f43c605fee0367382d9fdce2c67 to your computer and use it in GitHub Desktop.
Save Fleker/5d590f43c605fee0367382d9fdce2c67 to your computer and use it in GitHub Desktop.
Handle SYNC intent with user credentials
// Connect to Cloud Firestore
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
db.settings({timestampsInSnapshots: true});
app.onSync(async (body, headers) => {
const userEmail = await getEmail(headers);
const userDoc = await db.collection('users').doc(userEmail).get();
if (!userDoc.exists) {
// User account does not exist in database.
// TODO Create user
// Return an empty device array
return {
requestId: body.requestId,
payload: {
agentUserId: userEmail,
devices: []
}
}
}
const userDevices = await db.collection('users')
.doc(userEmail)
.collection('devices')
.get();
const devices = [];
userDevices.forEach(deviceDoc => {
const data = deviceDoc.data();
const device = {
id: doc.id,
type: data.type,
traits: data.traits,
name: {
defaultNames: data.defaultNames,
name: data.name,
nicknames: data.nicknames
},
deviceInfo: {
manufacturer: data.manufacturer,
model: data.model,
hwVersion: data.hwVersion,
swVersion: data.swVersion
},
willReportState: false,
attributes: {}
};
devices.push(device);
});
return {
requestId: body.requestId,
payload: {
agentUserId: userEmail,
devices
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment