how Apollo client optimisticResponse working - apollo

http://dev.apollodata.com/react/mutations.html
I am trying out with optimisticResponse, but i am confused... and couldn't get it working on my local.
My questions are:
will optimisticResponse update the props and hence the re-render? how important is __typename: 'Mutation' can you leave it?
updateQueries is for new record appear? is this function trigger automatically or you need to invoke it?
is there any full example of out there which include the apollo server side?

Solution found:
const networkInterface = createNetworkInterface('http://localhost:8080/graphql');
this.client = new ApolloClient({
networkInterface,
dataIdFromObject: r => r.id
}
);
dataIdFromObject is the one thing i am missing during the Apolloclient initiation
dataIdFromObject (Object) => string
A function that returns a object identifier given a particular result object.
it will give unique ID for all result object.

Related

EF CORE: How to modify owned collection on entity

I have entity "MyEntity" with a list of owners. Each owner object has 3 properties - Id, type, link.
In the configuration, I am mapping this like owned object.
builder.OwnsMany(a => a.Owner, ownershipBuilder =>
{
ownershipBuilder.HasKey(x => x.Link);
ownershipBuilder.Property(x => x.Id).IsRequired();
ownershipBuilder.Property(x => x.Type)
.HasConversion(t => t.ToString(),
value => (MyType) Enum.Parse(typeof(MyType), value))
.IsRequired();
});
Now, when I try to update this collection of owners, I got DbUpdateConcurrencyException
The flow of update is:
find parent entity by its ID
add owner into the list
call Update method on the dbContext and SaveChanges.
After calling savechanges I got mentioned exception.
Any idea here?
THX.
I solved it,
I am generating Link (Owner entity) in code and this is key in table also. Thus I must use ValueGeneratedNever in the entity configuration.
ownershipBuilder.Property(x => x.Link).ValueGeneratedNever().IsRequired();
Problem solved.

Apollo duplicates first result to every node in array of edges

I am working on a react app with react-apollo
calling data through graphql when I check in browser network tab response it shows all elements of the array different
but what I get or console.log() in my app then all elements of array same as the first element.
I don't know how to fix please help
The reason this happens is because the items in your array get "normalized" to the same values in the Apollo cache. AKA, they look the same to Apollo. This usually happens because they share the same Symbol(id).
If you print out your Apollo response object, you'll notice that each of the objects have Symbol(id) which is used by Apollo cache. Your array items probably have the same Symbol(id) which causes them to repeat. Why does this happen?
By default, Apollo cache runs this function for normalization.
export function defaultDataIdFromObject(result: any): string | null {
if (result.__typename) {
if (result.id !== undefined) {
return `${result.__typename}:${result.id}`;
}
if (result._id !== undefined) {
return `${result.__typename}:${result._id}`;
}
}
return null;
}
Your array item properties cause multiple items to return the same data id. In my case, multiple items had _id = null which caused all of these items to be repeated. When this function returns null the docs say
InMemoryCache will fall back to the path to the object in the query,
such as ROOT_QUERY.allPeople.0 for the first record returned on the
allPeople root query.
This is the behavior we actually want when our array items don't work well with defaultDataIdFromObject.
Therefore the solution is to manually configure these unique identifiers with the dataIdFromObject option passed to the InMemoryCache constructor within your ApolloClient. The following worked for me as all my objects use _id and had __typename.
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache({
dataIdFromObject: o => (o._id ? `${o.__typename}:${o._id}`: null),
})
});
Put this in your App.js
cache: new InMemoryCache({
dataIdFromObject: o => o.id ? `${o.__typename}-${o.id}` : `${o.__typename}-${o.cursor}`,
})
I believe the approach in other two answers should be avoided in favor of following approach:
Actually it is quite simple. To understand how it works simply log obj as follows:
dataIdFromObject: (obj) => {
let id = defaultDataIdFromObject(obj);
console.log('defaultDataIdFromObject OBJ ID', obj, id);
}
You will see that id will be null in your logs if you have this problem.
Pay attention to logged 'obj'. It will be printed for every object returned.
These objects are the ones from which Apollo tries to get unique id ( you have to tell to Apollo which field in your object is unique for each object in your array of 'items' returned from GraphQL - the same way you pass unique value for 'key' in React when you use 'map' or other iterations when rendering DOM elements).
From Apollo dox:
By default, InMemoryCache will attempt to use the commonly found
primary keys of id and _id for the unique identifier if they exist
along with __typename on an object.
So look at logged 'obj' used by 'defaultDataIdFromObject ' - if you don't see 'id' or '_id' then you should provide the field in your object that is unique for each object.
I changed example from Apollo dox to cover three cases when you may have provided incorrect identifiers - it is for cases when you have more than one GraphQL types:
dataIdFromObject: (obj) => {
let id = defaultDataIdFromObject(obj);
console.log('defaultDataIdFromObject OBJ ID', obj, id);
if (!id) {
const { __typename: typename } = obj;
switch (typename) {
case 'Blog': {
// if you are using other than 'id' and '_id' - 'blogId' in this case
const undef = `${typename}:${obj.id}`;
const defined = `${typename}:${obj.blogId}`;
console.log('in Blogs -', undef, defined);
return `${typename}:${obj.blogId}`; // return 'blogId' as it is a unique
//identifier. Using any other identifier will lead to above defined problem.
}
case 'Post': {
// if you are using hash key and sort key then hash key is not unique.
// If you do query in DB it will always be the same.
// If you do scan in DB quite often it will be the same value.
// So use both hash key and sort key instead to avoid the problem.
// Using both ensures ID used by Apollo is always unique.
// If for post you are using hashKey of blogID and sortKey of postId
const notUniq = `${typename}:${obj.blogId}`;
const notUniq2 = `${typename}:${obj.postId}`;
const uniq = `${typename}:${obj.blogId}${obj.postId}`;
console.log('in Post -', notUniq, notUniq2, uniq);
return `${typename}:${obj.blogId}${obj.postId}`;
}
case 'Comment': {
// lets assume 'comment's identifier is 'id'
// but you dont use it in your app and do not fetch from GraphQl, that is
// you omitted 'id' in your GraphQL query definition.
const undefnd = `${typename}:${obj.id}`;
console.log('in Comment -', undefnd);
// log result - null
// to fix it simply add 'id' in your GraphQL definition.
return `${typename}:${obj.id}`;
}
default: {
console.log('one falling to default-not good-define this in separate Case', ${typename});
return id;
}
I hope now you see that the approach in other two answers are risky.
YOU ALWAYS HAVE UNIQUE IDENTIFIER. SIMPLY HELP APOLLO BY LETTING KNOW WHICH FIELD IN OBJECT IT IS. If it is not fetched by adding in query definition add it.
An alternative option to the accepted is to instead of dataIdFromObject, which appears to be for everything in the query, I was able to provide a keyFields function per type that required it.
const client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
ItemType: {
keyFields: (obj) =>
obj.id + "-" + obj.language.id,
},
},
}),
});
In the above example ItemType can be whichever Type is specified in your schema. I happened to be joining a non-unique ID with a language to make a unique key but you can do it however you wish.

Symfony 3.2 - set environment variables in runtime [duplicate]

In my config.yml I have this:
parameters:
gitek.centro_por_defecto: 1
Now, I want to change this value from my controller using a form, like this:
public function seleccionAction(Request $request)
{
$entity = new Centro();
$form = $this->createForm(new SeleccionType(), $entity);
$centro = $this->container->getParameter('gitek.centro_por_defecto');
if ($this->getRequest()->getMethod() == 'POST') {
$form->bind($this->getRequest());
if ($form->isValid()) {
$miseleccion = $request->request->get('selecciontype');
$this->container->setParameter('gitek.centro_por_defecto', $miseleccion['nombre']);
// return $this->redirect($this->generateUrl('admin_centro'));
}
}
return $this->render('BackendBundle:Centro:seleccion.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
I´m getting Impossible to call set() on a frozen ParameterBag. error all the time.
Any help or clue?
You can't modify Container once it has been compiled, which is done before invoking the controller.
The DIC parameters are intended for configuration purposes - not a replacement for global variables. In addition it seems you want to persist some kind of permanent modification. In that case consider using session if it's a per-user modification or persisting it (e.g. into DB) if it's supposed to be application-wide.
If you need to modify DIC parameters or services, you can do so using a compiler pass. More info on how to write custom compiler passes can be found at:
http://symfony.com/doc/master/cookbook/service_container/compiler_passes.html
You can set $_ENV variables and get that after
putenv("VAR=1");
And to get
getenv("VAR");

acknowledge order report amazon mws

I am using "GetReportList" api with report list type as "_GET_ORDERS_DATA" to pull order reports from amazon. But I want to pull only new orders. How can I use the "acknowledged" field to make sure that I pull only new orders(which were not previously pulled).I observed that the "acknowledged" field is true by default. Please let me know if there is a way to pull new orders only(I am trying to avoid using timestamp here)
Thanks
You need to acknowledge the order report when you picked it up, then you will only get order reports set to acknowledged false on the next call.
So you need to run this operation:
$request1 = new MarketplaceWebService_Model_UpdateReportAcknowledgementsRequest();
$request1->setMerchant(MERCHANT_ID);
$idList1 = new MarketplaceWebService_Model_IdList();
$request1->setReportIdList($idList1->withId(/* SET THE REPORT ID YOU HAVE TAKEN */));
$request1->setAcknowledged(true);
invokeUpdateReportAcknowledgements($service, $request1);
function invokeUpdateReportAcknowledgements(MarketplaceWebService_Interface $service, $request1)
{
try {
$response = $service->updateReportAcknowledgements($request1);
} catch (MarketplaceWebService_Exception $ex) {
var_dump($ex);
After you have picked up the order report, and then, you can simply request the next order report with this line:
$request->setAcknowledged(false);
Like this, only reports you haven't set to acknowledged with the first call will be shown in the list.
The first call is described in the php API, I think it's called something like SetAcknowledgmentSample, and the second call needs to be called in the getReportListSample file
I think you can set them as below which I found from sample code found in Amazon Report's API sample
$parameters = array (
'Merchant' => MERCHANT_ID,
'AvailableToDate' => new DateTime('now', new DateTimeZone('UTC')),
'AvailableFromDate' => new DateTime('-6 months', new DateTimeZone('UTC')),
'Acknowledged' => false,
);
$request = new MarketplaceWebService_Model_GetReportListRequest($parameters);
$request = new MarketplaceWebService_Model_GetReportListRequest();
$request->setMerchant(MERCHANT_ID);
$request->setAvailableToDate(new DateTime('now', new DateTimeZone('UTC')));
$request->setAvailableFromDate(new DateTime('-3 months', new DateTimeZone('UTC')));
$request->setAcknowledged(false);

Symfony2: File Upload via Doctrine does not fire the PrePersist/PreUpdate lifecycle-event

i tried to implement the file upload via doctrine/lifecycle callbacks as described here:
http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html#using-lifecycle-callbacks
So far it works, but the PrePersist/PreUpdate Event is not fired, the function "preUpload" is not called.
Functions like "upload" and "removeUpload" triggered by other lifecycle events are called correctly.
Does anyone have an idea why the event is not fired or a solution for this problem?
Thanks
I have another solution to this problem:
My entity has a field "updatedAt" which is a timestamp of the last update. Since this field gets set anyway (by the timestampable extension of Gedmo) I just use this field to trick doctrine into believing that the entitiy was updated.
Before I persist the entity I set this field manually doing
if( $editForm['file']->getData() )
$entity->setUpdateAt(new \DateTime());
This way the entity gets persisted (because it has changed) and the preUpdate and postUpdate functions are called properly.
Of course this only works if your entity has a field that you can exploit like that.
You need to change tracking policies.
Full explanation.
there's a much simpler solution compared with changing tracking policies and other solutions:
in controller:
if ($form->isValid()) {
...
if ($form->get('file')->getData() != NULL) {//user have uploaded a new file
$file = $form->get('file')->getData();//get 'UploadedFile' object
$news->setPath($file->getClientOriginalName());//change field that holds file's path in db to a temporary value,i.e original file name uploaded by user
}
...
}
this way you have changed a persisted field (here it is path field), so PreUpdate() & PostUpdate() are triggered then you should change path field value to any thing you like (i.e timestamp) in PreUpdate() function so in the end correct value is persisted to DB.
A trick could be to modify the entity no matter what..on postLoad.
1 Create an updatedAt field.
/**
* Date/Time of the update
*
* #var \Datetime
* #ORM\Column(name="updated_at", type="datetime")
*/
private $updatedAt;
2 Create a postLoad() function that will modify your entity anyway:
/**
* #ORM\PostLoad()
*/
public function postLoad()
{
$this->updatedAt = new \DateTime();
}
3 Just update that field correctly on prePersist:
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
$this->updatedAt = new \DateTime();
//...update your picture
}
This is basically a slight variation of #philipphoffmann's answer:
What i do is that i modify an attribute before persisting to trigger the preUpdate event, then i undo this modification in the listener:
$entity->setToken($entity->getToken()."_tmp");
$em->flush();
In my listener:
public function preUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof MyEntity) {
$entity->setToken(str_replace('_tmp', '', $entity->getToken()));
//...
}
}
Another option is to display the database field where the filename is stored as a hidden input field and when the file upload input changes set that to empty so it ends up triggering doctrine's update events. So in the form builder you could have something like this:
->add('path', 'text', array('required' => false,'label' => 'Photo file name', 'attr' => array('class' => 'invisible')))
->add('file', 'file', array('label' => 'Photo', 'attr' => array('class' => 'uploader','data-target' => 'iddp_rorschachbundle_institutiontype_path')))
Path is a property managed by doctrine (equal to the field name in the db table) and file is the virtual property to handle uploads (not managed by doctrine). The css class simply sets the display to none. And then a simple js to change the value of the hidden input field
$('.uploader').change(function(){
var t = $(this).attr('data-target');
//clear input value
$("#"+t).val('');
});
For me, it worked good when I just manually called these methods in the controller.
Do you have checked your metadata cache driver option in your config.yml file?If it exists, just try to comment this line:
metadata_cache_driver: whateverTheStorage
Like this:
#metadata_cache_driver: whateverTheStorage