I'm trying to match infos from different places and construct the response for this function in firebase.
The problem is the return statements, they return an unexpected jSON
I need to fetch a match from the matchId, the match contains a list of playersId.
I need to get all the profiles for those players and return them.
Current code:
exports.getUsersForMatch = functions.https.onCall((data, context) => {
matchId = data.matchId;
return store.collection('match').doc(matchId).get().then(doc => {
return doc.data().playersid;
}).then(playersId => {
return combineUsers(playersId)
}).catch((error) => {
console.log("Error getting documents: ", error);
throw err;
});
});
function combineUsers(playersId) {
users = [];
for (var i = 0; i < playersId.length; i++) {
user = getUser(playersId[i])
users.push(user);
}
return Promise.all(users)
}
function getUser(userID) {
return store.collection('user').doc(userID).get().then(user => {
return user;
}).catch((error) => {
console.log("Error getting documents: ", error);
throw err;
});
}
From the app side i receive this:
[{
"_createTime": {
"_nanoseconds": 853961000,
"_seconds": 1563270188
},
"_fieldsProto": {
"number": {
"valueType": "integerValue",
"integerValue": "1"
},
"id": {
"stringValue": "SFWxifRwJ9crta4lpPUbLq5d34v1",
"valueType": "stringValue"
},
"point ": {
"valueType": "integerValue",
"integerValue": "0"
}
},
"_ref": {
"_firestore": {
"_clientPool": {
"clientFactory": {},
"concurrentOperationLimit": 100,
"activeClients": {}
},
"_settings": {
"firebaseVersion": "8.2.0",
"libName": "gccl",
"projectId": "***",
"libVersion": "2.2.4 fire/8.2.0"
},
"_lastSuccessfulRequest": 1563698812565,
"_settingsFrozen": true,
"_serializer": {
"timestampsInSnapshots": true,
"createReference": {}
},
"_preferTransactions": true,
"_projectId": "football-5290b"
},
"_path": {
"databaseId": "(default)",
"_projectId": "***"
"segments": ["user", "SFWxifRwJ9crta4lpPUbLq5d34v1"]
}
},
"_serializer": {
"timestampsInSnapshots": true,
"createReference": {}
},
"_readTime": {
"_nanoseconds": 491530000,
"_seconds": 1563698812
},
"_updateTime": {
"_nanoseconds": 179584000,
"_seconds": 1563304513
}
}, {
"_createTime": {
"_nanoseconds": 759742000,
"_seconds": 1563288148
},
"_fieldsProto": {
"number": {
"valueType": "integerValue",
"integerValue": "2"
},
"id": {
"stringValue": "S28K3KDrwYPjVHvSOHu29umCGra2",
"valueType": "stringValue"
},
"point ": {
"valueType": "integerValue",
"integerValue": "0"
}
},
"_ref": {
"_firestore": {
"_clientPool": {
"clientFactory": {},
"concurrentOperationLimit": 100,
"activeClients": {}
},
"_settings": {
"firebaseVersion": "8.2.0",
"libName": "gccl",
"_projectId": "***"
"libVersion": "2.2.4 fire/8.2.0"
},
"_lastSuccessfulRequest": 1563698812565,
"_settingsFrozen": true,
"_serializer": {
"timestampsInSnapshots": true,
"createReference": {}
},
"_preferTransactions": true,
"_projectId": "***"
},
"_path": {
"databaseId": "(default)",
"_projectId": "***"
"segments": ["user", "S28K3KDrwYPjVHvSOHu29umCGra2"]
}
},
"_serializer": {
"timestampsInSnapshots": true,
"createReference": {}
},
"_readTime": {
"_nanoseconds": 495247000,
"_seconds": 1563698812
},
"_updateTime": {
"_nanoseconds": 480467000,
"_seconds": 1563304509
}
}]
Related
I'm just getting started with using normalizr with Redux, and I can't make it work. Even though I can do it with plain JavaScript.
I have an array of objects
const data = [
{
data_detail: [
{
category: 'newCategory',
_id: '123',
},
],
_id: 'abc_id',
customer: {
_id: '456',
email: 'hello#gmail.com',
name: 'Bob',
},
date: '2021-01-10T01:51:24.387Z',
},
];
And I need to transform it to
const normalizedResponse = {
customers: {
'456': {
_id: '456',
email: 'hello#gmail.com',
name: 'Bob',
},
},
details: {
'123': {
category: 'newCategory',
_id: '123',
},
},
orders: {
'abc_id: {
order_detail: [123],
_id: 'abc_id',
customer: '456',
date: '2021-01-10T01:51:24.387Z',
},
},
};
Step 1: Display just orders
What I do:
const userSchema = new schema.Entity(
'orders',
);
const userListSchema = new schema.Array(userSchema);
const normalizedData = normalize(data, userListSchema);
What I get
{
"entities": {
"orders": {
"abc_id": {
"data_detail": [
{
"category": "newCategory",
"id": "123"
}
],
"id": "abc_id",
"customer": {
"id": "456",
"email": "hello#gmail.com",
"name": "Bob"
},
"date": "2021-01-10T01:51:24.387Z"
},
"abc_id-02": {
"data_detail": [
{
"category": "newCategory1",
"id": "123-02"
}
],
"id": "abc_id-02",
"customer": {
"id": "456-02",
"email": "hello#gmail.com",
"name": "Bob"
},
"date": "2001-01-10T01:51:24.387Z"
}
}
},
"result": [
"abc_id",
"abc_id-02"
]
}
What I'm trying to get:
orders: {
'abc_id: {
order_detail: [123],
_id: 'abc_id',
customer: '456',
date: '2021-01-10T01:51:24.387Z',
},
},
The question: How to remove some fields from orders and add new ones?
You have 3 different entity types in your data object. First draft out a schema for each of them:
const detail = new schema.Entity('details');
const customer = new schema.Entity('customers');
const order = new schema.Entity('orders');
Then go back and fill in the relationships. It looks like order is the outermost entity. An order contains an array of details/categories and a single customer.
const order = new schema.Entity('orders', {
data_detail: [detail],
customer,
});
All of your entities use _id instead of id, so you need to set the idAttribute.
Your data is an array of order. You can use new schema.Array(order) but you can also just use [order].
Here's your final code:
const customer = new schema.Entity("customers", {}, { idAttribute: "_id" });
const detail = new schema.Entity("details", {}, { idAttribute: "_id" });
const order = new schema.Entity(
"orders",
{
data_detail: [detail],
customer
},
{ idAttribute: "_id" }
);
const normalizedData = normalize(data, [order]);
That gives you:
{
"entities": {
"details": {
"123": {
"category": "newCategory",
"_id": "123"
}
},
"customers": {
"456": {
"_id": "456",
"email": "hello#gmail.com",
"name": "Bob"
}
},
"orders": {
"abc_id": {
"data_detail": ["123"],
"_id": "abc_id",
"customer": "456",
"date": "2021-01-10T01:51:24.387Z"
}
}
},
"result": ["abc_id"]
}
I need to create a dynamo db table with some attribute values using a Cloudformation template as follows:
PhoneNumber | OrderNumber
223546421 11545154
784578745 11547854
223458784 11547487
XXXXXXXXX 11578451
Were "XXXXXXXXX" is passed as a parameter.
Cloudformation template:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"OrdersTable": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
"TableName": "ClientOrders",
"AttributeDefinitions": [
{
"AttributeName": "PhoneNumber",
"AttributeType": "S"
},
{
"AttributeName": "OrderNumber",
"AttributeType": "S"
}
],
"KeySchema": [
{
"AttributeName": "PhoneNumber",
"KeyType": "HASH"
},
{
"AttributeName": "OrderNumber",
"KeyType": "RANGE"
}
],
"TimeToLiveSpecification": {
"AttributeName": "ExpirationTime",
"Enabled": true
},
"ProvisionedThroughput": {
"ReadCapacityUnits": "10",
"WriteCapacityUnits": "5"
}
},
"DependsOn": [
"DynamoDBQueryPolicy"
]
},
"DynamoDBQueryPolicy": {
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": "DynamoDBQueryPolicy",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "dynamodb:Query",
"Resource": "*"
}
]
},
"Roles": [
{
"Ref": "OrdersTableQueryRole"
}
]
}
},
"OrdersTableQueryRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"dynamodb.amazonaws.com"
]
},
"Action": [
"sts:AssumeRole"
]
}
]
},
"Path": "/"
}
},
"MyPhone223546421": {
"Type": "Custom::CrtUpdDltDynamodbDocumentLambda",
"Properties": {
"ServiceToken": "arn:aws:lambda:us-east-1:accountid:function:cfn-crt-upd-dlt-dynamodb-document",
"DynamoTableName": "ClientOrders",
"DynamoKeyProperty": "PhoneNumber",
"DynamoItem": "{\n \"PhoneNumber\": \"223546421\",\n \"OrderNumber\": \"11545154\",\n \"someKey\": \"someValue\"\n}\n"
}
},
"MyPhone784578745": {
"Type": "Custom::CrtUpdDltDynamodbDocumentLambda",
"Properties": {
"ServiceToken": "arn:aws:lambda:us-east-1:accountid:function:cfn-crt-upd-dlt-dynamodb-document",
"DynamoTableName": "ClientOrders",
"DynamoKeyProperty": "PhoneNumber",
"DynamoItem": "{\n \"PhoneNumber\": \"784578745\",\n \"OrderNumber\": \"11547854\",\n \"someKey\": \"someValue\"\n}\n"
}
}
}
}
It hangs when calling the lambda, of course this needs proper edition but im lacking skills to properly set it. This is the CF template for the lambda:
AWSTemplateFormatVersion: '2010-09-09'
Resources:
DynamoCfnLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: '/'
Policies:
- PolicyName: dynamodbAccessRole
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- dynamodb:*
Resource: '*'
- Effect: Allow
Action:
- logs:*
Resource: '*'
CfnCrtUpdDltDynamodbDocumentLambda:
Type: AWS::Lambda::Function
Properties:
FunctionName: 'cfn-crt-upd-dlt-dynamodb-document'
Code:
ZipFile: >
const AWS = require("aws-sdk");
const response = require("./cfn-response");
const docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = function(event, context) {
console.log(JSON.stringify(event, null, 2));
var item = JSON.parse(event.ResourceProperties.DynamoItem);
var keyProperty = event.ResourceProperties.DynamoKeyProperty;
var tableName = event.ResourceProperties.DynamoTableName;
if (event.RequestType == "Create" || event.RequestType == "Update") {
console.log("item:", item);
var params = {
TableName: tableName,
Item: item
};
console.log("Creating or Updating Document");
docClient.put(params, function(err, data) {
if (err) {
console.log('error creating/updating document', err);
response.send(event, context, "FAILED", {}, tableName + '_' + item[keyProperty]);
} else {
response.send(event, context, "SUCCESS", {}, tableName + '_' + item[keyProperty]);
}
});
}
if (event.RequestType == "Delete") {
console.log("Deleting a Document");
var params = {
TableName: tableName,
Key: {
[keyProperty]: item[keyProperty]
}
};
docClient.delete(params, function(err, data) {
if (err) {
response.send(event, context, "FAILED", {});
} else {
response.send(event, context, "SUCCESS", {});
}
});
}
};
Handler: index.handler
Role: !GetAtt DynamoCfnLambdaRole.Arn
Runtime: nodejs10.x
Timeout: 60
Would really appreciate some detailed explanation if someone has the time.
Thanks in advance.
when i say get me in the end, it would not trigger that intent that i intent to trigger.
/* *
This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK (v2).
Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management,
session persistence, api calls, and more.
*/
const Alexa = require('ask-sdk-core');
const msg = require("./localisation");
const constants = require("./constants");
const getSlotValues = (handlerInput) => {
return handlerInput.requestEnvelope.request.intent.slots;
}
const LaunchRequestHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest';
},
handle(handlerInput) {
const speakOutput = msg.HELLO_MSG;
return handlerInput.responseBuilder
.speak(speakOutput)
.reprompt(speakOutput)
.getResponse();
}
};
//If user the say follow up, we are going to ask another question.
const FollowUpIntentHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
&& Alexa.getIntentName(handlerInput.requestEnvelope) === 'FollowUpIntentHandler';
},
handle(handlerInput) {
const {responseBuilder, attributesManager} = handlerInput;
const slotValue = getSlotValues(handlerInput);
const sessionAttribute = attributesManager.getSessionAttributes();
sessionAttribute['follow']= slotValue.follow.value;
// const sessionAttribute = attributeManager.getSessionAttributes();
// const slotValues = getSlotValues(handlerInput);
// sessionAttribute["follow"] = slotValues.follow.value;
const speakOutput = msg.FOLLOW_UP_QUESTION_MSG;
return responseBuilder
.speak(speakOutput)
//.reprompt('add a reprompt if you want to keep the session open for the user to respond')
.getResponse();
}
};
//If user the say new we are going to ask another question.
const NewIntentHandler = {
canHandle(handlerInput){
const {request} = handlerInput.requestEnvelope;
return request.type === 'IntentRequest'
&& request.intent.name === "NewIntentHandler";
},
handle(handlerInput){
const {responseBuilder, attributeManager} = handlerInput;
const sessionAttribute = attributeManager.getSessionAttributes();
const slotValues = getSlotValues(handlerInput);
sessionAttribute["new"] = slotValues.new.value;
const speakOutput = msg.NEW_QUESTION_MSG;
return responseBuilder.speak(speakOutput).reprompt(speakOutput).getResponse();
}
};
const CaptureUserQuestionIntentHandler = {
canHandle(handlerInput){
const {request} = handlerInput.requestEnvelope;
const {attributesManager} = handlerInput;
const sessionAttribute = attributesManager.getSessionAttributes();
return request.type === "IntentRequest"
&& request.intent.name === "CaptureUserQuestionIntentHandler"
|| sessionAttribute['new']
|| sessionAttribute['follow'];
},
handle(handlerInput){
const slotValue = getSlotValues(handlerInput);
const {responseBuilder, attributesManager} = handlerInput;
const sessionAttribute = attributesManager.getSessionAttributes();
sessionAttribute["bodyPart"] = slotValue.bodyPart.value;
sessionAttribute["drainage"] = slotValue.drainage.value;
sessionAttribute["time"] = slotValue.time.value;
// const bodyPart = slotValue.bodyPart.value;
// const time = slotValue.time.value;
// const drainage = slotValue.drainage.value;
const speakOutput = `What is the ${sessionAttribute['drainage']} coming from? The back of the ear near the incision or the opening of your ear or ear canal?`;
return responseBuilder
.speak(speakOutput)
//.reprompt(speakOutput)
.getResponse()
}
};
const BackOrNearIncisionIntentHandler = {
canHandle(handlerInput){
const {request} = handlerInput.requestEnvelope;
const {attributesManager} = handlerInput;
const sessionAttribute = attributesManager.getSessionAttributes();
return request.type === "IntentRequest"
&& request.intent.name === "BackOrNearIncisionIntentHandler"
&& sessionAttribute["drainage"];
},
handle(handlerInput){
const slotValues = getSlotValues(handlerInput);
const {attributesManager, responseBuilder} = handlerInput;
const sessionAttribute = attributesManager.getSessionAttributes();
let speakOutput;
sessionAttribute['color'] = slotValues.color.value;
const color = sessionAttribute['color'];
if(color === constants.CLEAR){
speakOutput = msg.IMPORANT_GET_TREATED;
}else{
speakOutput = msg.SUGGEST_APPLY_MEDICINE;
}
return responseBuilder
.speak(speakOutput)
//.reprompt(speakOutput)
.getResponse()
}
};
const YesPleaseIntentHandler = {
canHandle(handlerInput){
const {request} = handlerInput.requestEnvelope;
const {attributesManager} = handlerInput;
const sessionAttribute = attributesManager.getSessionAttributes();
return request.type === "IntentRequest"
&& request.intent.name === "AMAZON.YesIntent"
&& sessionAttribute["color"] === constants.CLEAR;
},
handle(handlerInput){
const {responseBuilder} = handlerInput;
// let speakOutput = msg.YOUR_NEXT_APPOINTMENT;
let speakOutput = msg.YOUR_NEXT_APPOINTMENT;
return responseBuilder
.speak(speakOutput)
//.reprompt(speakOutput)
.getResponse()
}
};
const UserIntentHandlers = {
canHandle(handlerInput){
const {request} = handlerInput.requestEnvelope;
return request.type === "IntentRequest"
&& request.intent.name === "UserIntentHandler";
},
handle(handlerInput){
const {responseBuilder} = handlerInput;
// let speakOutput = msg.YOUR_NEXT_APPOINTMENT;
let speakOutput = msg.YOUR_NEXT_APPOINTMENT;
console.log(responseBuilder);
return responseBuilder
.speak(speakOutput)
//.reprompt(speakOutput)
.getResponse()
}
};
const HelpIntentHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
&& Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.HelpIntent';
},
handle(handlerInput) {
const speakOutput = 'You can say hello to me! How can I help?';
return handlerInput.responseBuilder
.speak(speakOutput)
.reprompt(speakOutput)
.getResponse();
}
};
const CancelAndStopIntentHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
&& (Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.CancelIntent'
|| Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.StopIntent');
},
handle(handlerInput) {
const speakOutput = 'Goodbye!';
return handlerInput.responseBuilder
.speak(speakOutput)
.getResponse();
}
};
/* *
* FallbackIntent triggers when a customer says something that doesn’t map to any intents in your skill
* It must also be defined in the language model (if the locale supports it)
* This handler can be safely added but will be ingnored in locales that do not support it yet
* */
const FallbackIntentHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
&& Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.FallbackIntent';
},
handle(handlerInput) {
const speakOutput = 'Sorry, I don\'t know about that. Please try again.';
return handlerInput.responseBuilder
.speak(speakOutput)
.reprompt(speakOutput)
.getResponse();
}
};
/* *
* SessionEndedRequest notifies that a session was ended. This handler will be triggered when a currently open
* session is closed for one of the following reasons: 1) The user says "exit" or "quit". 2) The user does not
* respond or says something that does not match an intent defined in your voice model. 3) An error occurs
* */
const SessionEndedRequestHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'SessionEndedRequest';
},
handle(handlerInput) {
console.log(`~~~~ Session ended: ${JSON.stringify(handlerInput.requestEnvelope)}`);
// Any cleanup logic goes here.
return handlerInput.responseBuilder.getResponse(); // notice we send an empty response
}
};
/* *
* The intent reflector is used for interaction model testing and debugging.
* It will simply repeat the intent the user said. You can create custom handlers for your intents
* by defining them above, then also adding them to the request handler chain below
* */
const IntentReflectorHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest';
},
handle(handlerInput) {
const intentName = Alexa.getIntentName(handlerInput.requestEnvelope);
const speakOutput = `You just triggered ${intentName}`;
return handlerInput.responseBuilder
.speak(speakOutput)
//.reprompt('add a reprompt if you want to keep the session open for the user to respond')
.getResponse();
}
};
/**
* Generic error handling to capture any syntax or routing errors. If you receive an error
* stating the request handler chain is not found, you have not implemented a handler for
* the intent being invoked or included it in the skill builder below
* */
const ErrorHandler = {
canHandle() {
return true;
},
handle(handlerInput, error) {
const speakOutput = 'Sorry, I had trouble doing what you asked. Please try again.';
console.log(`~~~~ Error handled: ${JSON.stringify(error)}`);
return handlerInput.responseBuilder
.speak(speakOutput)
.reprompt(speakOutput)
.getResponse();
}
};
/**
* This handler acts as the entry point for your skill, routing all request and response
* payloads to the handlers above. Make sure any new handlers or interceptors you've
* defined are included below. The order matters - they're processed top to bottom
* */
exports.handler = Alexa.SkillBuilders.custom()
.addRequestHandlers(
LaunchRequestHandler,
YesPleaseIntentHandler,
FollowUpIntentHandler,
BackOrNearIncisionIntentHandler,
NewIntentHandler,
CaptureUserQuestionIntentHandler,
UserIntentHandlers,
HelpIntentHandler,
CancelAndStopIntentHandler,
FallbackIntentHandler,
SessionEndedRequestHandler,
IntentReflectorHandler)
.addErrorHandlers(
ErrorHandler)
.withCustomUserAgent('sample/hello-world/v1.2')
.lambda();
{
"interactionModel": {
"languageModel": {
"invocationName": "lee healthcare",
"intents": [
{
"name": "AMAZON.CancelIntent",
"samples": []
},
{
"name": "AMAZON.HelpIntent",
"samples": []
},
{
"name": "AMAZON.StopIntent",
"samples": []
},
{
"name": "AMAZON.NavigateHomeIntent",
"samples": []
},
{
"name": "AMAZON.FallbackIntent",
"samples": []
},
{
"name": "FollowUpIntentHandler",
"slots": [
{
"name": "follow",
"type": "FOLLOW"
}
],
"samples": [
"{follow} up question",
"{follow} up",
"{follow}"
]
},
{
"name": "NewIntentHandler",
"slots": [
{
"name": "new",
"type": "NEW"
}
],
"samples": [
"{new} question",
"{new}"
]
},
{
"name": "CaptureUserQuestionIntentHandler",
"slots": [
{
"name": "bodyPart",
"type": "BODYPARTS"
},
{
"name": "time",
"type": "customDate",
"samples": [
"{time}"
]
},
{
"name": "drainage",
"type": "DRAIN",
"samples": [
"{drainage}"
]
}
],
"samples": [
"I have {bodyPart} surgery {time} and have {drainage}"
]
},
{
"name": "BackOrNearIncisionIntentHandler",
"slots": [
{
"name": "color",
"type": "AMAZON.Color",
"samples": [
"{color}"
]
}
],
"samples": [
"{color}",
"near the incision",
"back of the ear near the incision"
]
},
{
"name": "AMAZON.YesIntent",
"samples": []
},
{
"name": "UserIntentHandler",
"slots": [],
"samples": [
"get me"
]
}
],
"types": [
{
"name": "FOLLOW",
"values": [
{
"name": {
"value": "follow"
}
}
]
},
{
"name": "NEW",
"values": [
{
"name": {
"value": "new"
}
}
]
},
{
"name": "BODYPARTS",
"values": [
{
"name": {
"value": "ear"
}
}
]
},
{
"name": "DRAIN",
"values": [
{
"name": {
"value": "drainage"
}
}
]
},
{
"name": "customDate",
"values": [
{
"name": {
"value": "last week"
}
}
]
},
{
"name": "AMAZON.Color",
"values": [
{
"name": {
"value": "clear"
}
}
]
}
]
},
"dialog": {
"intents": [
{
"name": "CaptureUserQuestionIntentHandler",
"confirmationRequired": false,
"prompts": {},
"slots": [
{
"name": "bodyPart",
"type": "BODYPARTS",
"confirmationRequired": false,
"elicitationRequired": false,
"prompts": {}
},
{
"name": "time",
"type": "customDate",
"confirmationRequired": false,
"elicitationRequired": true,
"prompts": {
"elicitation": "Elicit.Slot.832794320406.761354353518"
}
},
{
"name": "drainage",
"type": "DRAIN",
"confirmationRequired": false,
"elicitationRequired": true,
"prompts": {
"elicitation": "Elicit.Slot.832794320406.873931110175"
}
}
]
},
{
"name": "BackOrNearIncisionIntentHandler",
"confirmationRequired": false,
"prompts": {},
"slots": [
{
"name": "color",
"type": "AMAZON.Color",
"confirmationRequired": false,
"elicitationRequired": true,
"prompts": {
"elicitation": "Elicit.Slot.414884367204.126479337664"
}
}
]
}
],
"delegationStrategy": "ALWAYS"
},
"prompts": [
{
"id": "Slot.Validation.544061479456.1369268390684.618525999294",
"variations": [
{
"type": "PlainText",
"value": "Can i help you with the follow question or new question?"
}
]
},
{
"id": "Elicit.Slot.832794320406.761354353518",
"variations": [
{
"type": "PlainText",
"value": "When does it happen?"
}
]
},
{
"id": "Elicit.Slot.832794320406.873931110175",
"variations": [
{
"type": "PlainText",
"value": "What else do you have ?"
}
]
},
{
"id": "Elicit.Slot.414884367204.126479337664",
"variations": [
{
"type": "PlainText",
"value": "What color is drainage?"
}
]
}
]
}
}
Are you still having this problem? When I created a new skill using your code and interaction model, "get me" successfully triggered the UserIntentHandlers. What intent is getting triggered?
In the Alexa Developer Console, in the "Build" tab for your skill, click "Intents" in the side menu. You'll see an "Evaluate Model" button near the top right. Click it and choose "Utterance Profiler". You can see what intent gets triggered when you say "get me".
So I've been playing around with the firebase firestore feature for my REST API backend for a Godot project I'm working on. I'm using HTTP requests to post and get data from the database. So far I've only been using simple types of data, associating one user's ID to his or her username as a string.
In my code, I've defined a function that is responsible for doing the actual saving of a new file through an HTTP request:
func save_document(path: String, fields: Dictionary, http: HTTPRequest) -> void:
var document = { "fields": fields }
var body = to_json(document)
var url = FIRESTORE_URL + path
var res = http.request(url, _get_request_headers(), false, HTTPClient.METHOD_POST, body)
if res == OK:
print("successfully created document")
else:
print("failed creating document")
Then I call the function:
var payload_body_1 = {
"name": {
"stringValue": username.text
}
}
save_document("users?documentId=%s" % firebase.user_info.id, payload_body_1, http)
All of the above works 100% fine. But when I try to post more complicated data, such as a dictionary of dictionaries of dictionaries, I run into some problems.
When I run the following code:
var res = {
"north": {"spades": [], "hearts": [], "diamonds": [], "clubs": []},
"south": {"spades": [], "hearts": [], "diamonds": [], "clubs": []},
"east": {"spades": [], "hearts": [], "diamonds": [], "clubs": []},
"west": {"spades": [], "hearts": [], "diamonds": [], "clubs": []},
}
save_document("online?documentId=test", res, http)
It doesn't work. I imagine it has something to do with the "stringValue" key I used in the case where it worked, but I can't seem to figure out what to do when the value isn't a string value. Does anyone know how to solve this?
Ok so I actually solved it but I thought I might as well post the answer here if someone else potentially has the same problem in the future.
So basically, every field needs a data type, for instance, "stringValue". for Dictionaries, you need "mapValue", and for lists, you need "arrayValue". In the above Example, you would need to use some code looking like this:
var res = {
"north": { "mapValue": { "fields": {
"spades": { "arrayValue": { "values": [] } },
"hearts": { "arrayValue": { "values": [] } },
"diamonds": { "arrayValue": { "values": [] } },
"clubs": { "arrayValue": { "values": [] } }
} } },
"south": { "mapValue": { "fields": {
"spades": { "arrayValue": { "values": [] } },
"hearts": { "arrayValue": { "values": [] } },
"diamonds": { "arrayValue": { "values": [] } },
"clubs": { "arrayValue": { "values": [] } }
} } },
"east": { "mapValue": { "fields": {
"spades": { "arrayValue": { "values": [] } },
"hearts": { "arrayValue": { "values": [] } },
"diamonds": { "arrayValue": { "values": [] } },
"clubs": { "arrayValue": { "values": [] } }
} } },
"west": { "mapValue": { "fields": {
"spades": { "arrayValue": { "values": [] } },
"hearts": { "arrayValue": { "values": [] } },
"diamonds": { "arrayValue": { "values": [] } },
"clubs": { "arrayValue": { "values": [] } }
} } }
}
the mapValues need the "fields" key which is a dictionary of the keys in the dictionary associated with "mapValue". The arrayValues need something similar, but "values" instead of "fields". each element of the array in values should be a dictionary, and if you want the array for example to contain strings, each element should look like:
{ "stringValue": "text" }
> Locate the `displayBirthdate` function you initially defined, which took no parameter. Modify it to use object de-structuring to get just the 'dob' property of the parameter object it will receive
here's the code
```javascript
const displayBirthdate = () => {};
const displayAddress = () => {};
const displayExtraUserInfo = (extra) => {
document.getElementById("btn-birthdate").addEventListener("click", ()=>
{ displayBirthdate(extra) })
document.getElementById("btn-phone").addEventListener("click", () =>
{ displayPhone(extra) })
document.getElementById("btn-address").addEventListener("click", () =>
{ displayAddress(extra) })
```
adding to the above question
this is the expected response passed as parameter extra
{
"results": [
{
"gender": "female",
"name": {
"title": "ms",
"first": "ceyhan",
"last": "dizdar"
},
"location": {
"street": "3826 şehitler cd",
"city": "tekirdağ",
"state": "bitlis",
"postcode": 11689,
"coordinates": {
"latitude": "79.1017",
"longitude": "27.1350"
},
"timezone": {
"offset": "+5:45",
"description": "Kathmandu"
}
},
"email": "ceyhan.dizdar#example.com",
"login": {
"uuid": "34eb65b2-0535-4656-bd68-4da69dc6d016",
"username": "orangefish864",
"password": "grandpa",
"salt": "vowzvAS2",
"md5": "cf4a7f3210ef97e8e72defafd80b94c8",
"sha1": "4f2af3439862b9bf25757ee73df8cd410ce201a2",
"sha256":
"1497acbca446b5fa47d4bc5ffe4e82c17818176596b66d94f213f091c8ed8077"
},
"dob": {
"date": "1979-08-10T22:03:55Z",
"age": 39
},
"registered": {
"date": "2008-05-24T13:30:20Z",
"age": 10
},
"phone": "(873)-801-4132",
"cell": "(751)-606-5317",
"id": {
"name": "",
"value": null
},
"picture": {
"large": "https://randomuser.me/api/portraits/women/59.jpg",
"medium": "https://randomuser.me/api/portraits/med/women/59.jpg",
"thumbnail":
"https://randomuser.me/api/portraits/thumb/women/59.jpg"
},
"nat": "TR"
}
],
"info": {
"seed": "008a9fe3a638239b",
"results": 1,
"page": 1,
"version": "1.2"
}
}
Now the question is this:
write an arrow function example displayBirthdate(), pass in this object(extra) as a parameter. using de-structuring method, grab the "dob" property in the object(extra).
below is how i have attempted to solve the question:
const displayBirthdate = (obj) =>{
const{results} = obj;
const[{dob}] = results;
}
but it appears to be incorrect. please any help would be appreciated. thank you
const displayBirthdate = ({dob}) => {};
const displayAddress ({location}) =>{};
In your attempted solution, you were trying to obtain the dob object
from results, but const{results} = obj; evaluates results to
an array. const {dob} = results[0]; in my answer gets the dob object from the first element in the results array. Cheers!
const displayBirthdate = (obj) =>{
const{results} = obj;
const[{dob}] = results;
}
const displayBirthdate = (obj) =>{
const {results} = obj;
console.log(results); // this is an array with the required object at index = 0
const {dob} = results[0];
console.log(dob); // dob is the object you are looking for
}