Reading a Fragment from the Apollo Cache with client.readFragment() - apollo

After successfully executing a query, I can see the following (image attached) using Apollo Dev Tools.
However, I'm unable to query for a filter object directly with the ID, say, 2025. I'm getting an Uncaught Invariant Violation: Can't find field filters on ROOT_QUERY object.
Here's how I'm trying to query:
client.cache.readQuery({
query: gql`
query Filter {
filters {
key
value
}
}
`
});
I also tried with fragment as follows:
client.readFragment({
id: '2025',
fragment: gql`
fragment filter on filters {
id
key
value
}
`
});
But that gives me null.

You need to specify the object with the__typename and id that you are querying out of the cache. Notice that the id of the filters object is filters:[id] inside the Apollo Cache, that is the format you need to use to access that fragment in the cache, [__typename]:[key]. You can read more about assigning cache identifiers in the docs.
You access your fragment using the following:
const filter = client.readFragment({
fragment: gql`
fragment filter on filters {
id
key
value
}
`,
fragmentName: 'filter',
id: 'filter:2025'
})

Related

AWS AppSync RDS: $util.rds.toJSONObject() Nested Objects

I am using Amazon RDS with AppSync. I've created a resolver that join two tables to get One-to-One association between them and returns columns from both tables. What I would like to do is to be able to put nest some columns under a key in the resulting parsed JSON object evaluated using $util.rds.toJSONObject().
Here's the schema:
type Parent {
col1: String
col2: String
child: Child
}
type Child {
col3: String
col4: String
}
Here's the resolver:
{
"version": "2018-05-29",
"statements": [
"SELECT parent.*, child.col3 AS `child.col3`, child.col4 AS `child.col4` FROM parent LEFT JOIN child ON parent.col1 = child.col3"
]
}
I tried naming the resulting column with dot-syntax but, $util.rds.toJSONObject() doesn't put col3 and col4 under child key. The reason it should is because otherwise, Apollo won't be able to cache and parse the entity.
Note: Dot-syntax is not documented anywhere. Usually, some ORMs use dot-syntax technique to convert SQL rows to proper nested JSON objects.
The #Aaron_H comment and answer were useful for me, but the response mapping template provided in the answer didn't work for me.
I managed to get a working response mapping template for my case which is similar for the case in question. In images below you will find info for query -> message(id: ID) { ... } (one message and the associated user will be returned):
SQL request to user table;
SQL request to message table;
SQL JOIN tables request for message id=1;
GraphQL Schema;
Request and response templates;
AWS AppSync query.
https://github.com/xai1983kbu/apollo-server/blob/pulumi_appsync_2/bff_pulumi/graphql/resolvers/Query.message.js
Next example for query messages
https://github.com/xai1983kbu/apollo-server/blob/pulumi_appsync_2/bff_pulumi/graphql/resolvers/Query.messages.js
Assuming your resolver is expecting to return a list of Parent types, ie. [Parent!]!, you can write your response mapping template logic like this:
#if($ctx.error)
$util.error($ctx.error.message, $ctx.error.type)
#end
#set($output = $utils.rds.toJsonObject($ctx.result)[0])
## Make sure to handle instances where fields are null
## or don't exist according to your business logic
#foreach( $item in $output )
#set($item.child = {
"col3": $item.get("child.col3"),
"col4": $item.get("child.col4")
})
#end
$util.toJson($output)

Is it possible to get reports by filtering using power bi rest api?

Is it possible to get reports by filtering using power bi rest api? I want to embed power bi reports filtering by records. I can't see any option on power bi rest api, then how to get all reports by filter and embed reports in my application?
Since I am using powerbi.js as javascript client so below is my sample code:
https://github.com/Microsoft/PowerBI-JavaScript
var tokenType = 'embed';
// Get models. models contains enums that can be used.
var models = window['powerbi-client'].models;
// We give All permissions to demonstrate switching between View and
//Edit mode and saving report.
var permissions = models.Permissions.All;
var config = {
type: 'report',
tokenType: tokenType == '0' ? models.TokenType.Aad :
models.TokenType.Embed,
accessToken: txtAccessToken,
embedUrl: txtEmbedUrl,
id: txtEmbedReportId,
permissions: permissions,
settings: {
filterPaneEnabled: true,
navContentPaneEnabled: true
}
};
// Get a reference to the embedded report HTML element
var embedContainer = $('#embedContainer')[0];
// Embed the report and display it within the div container.
var report = (<any>window).powerbi.embed(embedContainer, config);
When you are embedding a report, you can use the Embed Configuration to apply filters when the report is loaded. You can also change the filters dynamically later.
Here is a quote from filters wiki:
Filters are JavaScript objects that have a special set of properties. Currently, there are five types of filters: Basic, Advanced, Relative Date, Top N and Include/Exclude, which match the types of filters you can create through the filter pane. There are corresponding interfaces IBasicFilter, IAdvancedFilter, IRelativeDateFilter, ITopNFilter and IIncludeExcludeFilter, which describe their required properties.
For example, your filter can be constructed like this:
const basicFilter: pbi.models.IBasicFilter = {
$schema: "http://powerbi.com/product/schema#basic",
target: {
table: "Sales",
column: "AccountId"
},
operator: "In",
values: [1,2,3],
filterType: pbi.models.FilterType.BasicFilter
}
You should pass this filter in report's configuration filters property.

Apollo Client: Network Error {"type":"WriteError"}

I am getting Network Error {"type":"WriteError"} on my apollo query. Query executes just fine as well as it arrives to the client. But there is issue writing it tot he store. Any ides what can be going wrong? This is the query:
fragment BpmnProcessInstanceItemTask on BpmnTaskInstance {
id
dateStarted
dateFinished
task {
name
__typename
}
performer {
name
__typename
}
performerRoles
__typename
}
fragment BpmnProcessInstanceItem on BpmnProcessInstance {
id
status
process {
name
description
type
__typename
}
owner {
name
__typename
}
tasks {
...BpmnProcessInstanceItemTask
__typename
}
dateStarted
dateFinished
__typename
}
query BpmnProcessInstancesQuery($input: BpmnProcessInstancesInput!) {
bpmnProcessInstancesQuery(input: $input) {
...BpmnProcessInstanceItem
__typename
}
}
"
I just ran into this myself, and found the solution here. It's happening because the query is loading data without an id (or ids), which then can't be merged with the existing data in the cache.
Take the following example query:
{
viewer {
id
fullName
groups {
id
name
}
}
}
The returned data will be stored in the cache with one entry for the viewer and one entry per group:
User:asidnajksduih6
Group:9p8h2uidbjqshd
Group:d9a78h92lnasax
If a subsequent query looked like:
{
viewer {
id
fullName
groups {
name
}
}
}
There could be a conflict because it's unclear which groups should be updated in the cache (the result set will not include group ids).
The solution appears to be to always use ids in your queries wherever possible. This avoids the merge issue and it improves the chances for subsequent unrelated queries to have a cache hit.
The above describes a cause and a solution. Possible symptoms of this problem include: rendering stale data, or rendering no data even though the results are in your cache. As pointed out here, these errors happen silently, however they can be seen via the Apollo chrome extension in the "queries" tab.
The BpmnProcessInstanceItemTask fragment if overlapping the existing tasks object through the __typename field. The same in this code:
query BpmnProcessInstancesQuery($input: BpmnProcessInstancesInput!) {
bpmnProcessInstancesQuery(input: $input) {
...BpmnProcessInstanceItem
__typename <-- *same field stored twice*
}
}

Google Cloud Datastore query values in array

I have entities that look like that:
{
name: "Max",
nicknames: [
"bestuser"
]
}
how can I query for nicknames to get the name?
I have created the following index,
indexes:
- kind: users
properties:
- name: name
- name: nicknames
I use the node.js client library to query the nickname,
db.createQuery('default','users').filter('nicknames', '=', 'bestuser')
the response is only an empty array.
Is there a way to do that?
You need to actually fetch the query from datastore, not just create the query. I'm not familiar with the nodejs library, but this is the code given on the Google Cloud website:
datastore.runQuery(query).then(results => {
// Task entities found.
const tasks = results[0];
console.log('Tasks:');
tasks.forEach(task => console.log(task));
});
where query would be
const query = db.createQuery('default','users').filter('nicknames', '=', 'bestuser')
Check the documentation at https://cloud.google.com/datastore/docs/concepts/queries#datastore-datastore-run-query-nodejs
The first point to notice is that you don't need to create an index to this kind of search. No inequalities, no orders and no projections, so it is unnecessary.
As Reuben mentioned, you've created the query but you didn't run it.
ds.runQuery(query, (err, entities, info) => {
if (err) {
reject(err);
} else {
response.resultStatus = info.moreResults;
response.cursor = info.moreResults == TNoMoreResults? null: info.endCursor;
resolve(entities);
};
});
In my case, the response structure was made to collect information on the cursor (if there is more data than I've queried because I've limited the query size using limit) but you don't need to anything more than the resolve(entities)
If you are using the default namespace you need to remove it from your query. Your query needs to be like this:
const query = db.createQuery('users').filter('nicknames', '=', 'bestuser')
I read the entire plob as a string to get the bytes of a binary file here. I imagine you simply parse the Json per your requirement

Error when querying a type with unfilled attribute

I created the schema and resources (the DynamoDB tables), and I also attached the needed resolvers. Here is the screenshot of the User table with some sample data.
Sample data
For the first user, there are only id and username. Other fields are empty. When I query this user in AppSync console, there will be some error.
Query Error
Here is the query I used:
query getUser{
getUser(id:"5d0a2154-b828-4bcb-a34a-07503fe4b458"){
id
username
userProfile{
id
lastName
firstName
}
school{
id
schoolName
schoolAddress
}
role{
name
}
studentCourseSessions{
id
notes
}
programs{
name
courses{
name
}
}
}
}
And here is the VTL for the getUser query
Seems like, if a field is empty, there will be an error. I want, if the field is not filled, it should return "null". It can still return error but I need the "null" as well.
I am new to AppSync and DynamoDB.