Updating a Contentful entry - contentful

I've hit a brick wall whilst attempting to update a Contentful entry using a typical http request in Javascript; I receive the error code "VersionMismatch" which, according to the documentation, means:
This error occurs when you're trying to update an existing asset,
entry or content type, and you didn't specify the current version of
the object or specify an outdated version.
However, I have specified the current version of the entry using the 'X-Contentful-Version' header parameter as per the documentation, and have used the dynamic property value from 'entry.sys.revision' as the parameter value (as well as hardcoding the current version, plus a bunch of different numbers, but I always receive the same error). This post reported the exact same issue, but was seemingly resolved by adding this header parameter.
Here's my current code, that is also using the Contentful API to retrieve entries from my Contentful space, but I'm having to use plain Javascript to put the data back due to specific requirements:
var client = contentful.createClient(
{
space: space_id,
accessToken: client_token
}
);
client.getEntry(entry_id).then((entry) => entry).then(function(entry) {
// update values of entry
entry.fields.title = "Testing";
// post data to contentful API
var request = new XMLHttpRequest();
request.open('PUT', 'https://api.contentful.com/spaces/' + space_id + '/entries/' + entry_id);
request.setRequestHeader('Authorization', 'Bearer my_access_token');
request.setRequestHeader('Content-Type', 'application/vnd.contentful.management.v1+json');
request.setRequestHeader('X-Contentful-Content-Type', entry.sys.contentType.sys.id);
// setting the 'X-Contentful-Version' header with current/soon to be old version
request.setRequestHeader('X-Contentful-Version', entry.sys.revision);
// convert entry object to JSON before sending
var body = JSON.stringify({fields: entry.fields});
request.send(body);
});

Contentful developer here.
It looks like you get your content with the Contentful Delivery SDK and then try yo use that data to update content. That will not work. Instead I recommend using the Contentful Management SDK which will take care of all the versioning header for you.

I know its too late to answer here, but I am also facing same issue while doing this process.
So I asked this question and got the answer how we can achieve this without using Contentful-management sdk. My intention is not to suppress this sdk but we should be go to perform operation without it. I am trying to do it via postman but facing issue.
So I just post it and got the answer but understand the problem why I am not able to update the content because of two things
URL (api.contentful.com is the correct url if we are trying to update the content)
access_token (if we are using api.contentful.com which means we have to generate our personal token (management token) in the contentful, we cannot use preview/delivery tokens)
These are the highlighted point which we need to consider while doing update. I posted the link below may be it help someone in future.
Updating entry of Contentful using postman

Related

Method to clear pre-filled data of a ST.future.Component

Is there a way to clear an input field while using the ST.component("locator"); API?
Using ST.component("locator").setValue(""); results in the following error:
TypeError: ST.component(...).setValue is not a function...
PS: Is the old forum now permanently closed? Is there a way to view older questions?
Edit: Seems like the other forum was down yesterday, therefore the PS.
If it's an Ext JS field you will need to use the ST.field API in Sencha Test, which has a setValue method. This method isn't available on the more generic ST.component API.
ST.field('myfield')
.setValue('');
Or if it's a normal input field (not an Ext JS component), then you can do the following:
ST.element('#myfield')
.execute(function(field) {
field.dom.value = '';
});

Strapi & react-admin : I'd like to set 'Content-Range' header dynamically when any fetchAll query fires

I'm still a novice web developer, so please bear with me if I miss something fundamental !
I'm creating a backoffice for a Strapi backend, using react-admin.
React-admin library uses a 'data provider' to link itself with an API. Luckily someone already wrote a data provider for Strapi. I had no problem with step 1 and 2 of this README, and I can authenticate to Strapi within my React app.
I now want to fetch and display my Strapi data, starting with Users. In order to do that, quoting Step 3 of this readme : 'In controllers I need to set the Content-Range header with the total number of results to build the pagination'.
So far I tried to do this in my User controller, with no success.
What I try to achieve:
First, I'd like it to simply work with the ctx.set('Content-Range', ...) hard-coded in the controller like aforementioned Step 3.
Second, I've thought it would be very dirty to c/p this logic in every controller (not to mention in any future controllers), instead of having some callback function dynamically appending the Content-Range header to any fetchAll request. Ultimately that's what I aim for, because with ~40 Strapi objects to administrate already and plenty more to come, it has to scale.
Technical infos
node -v: 11.13.0
npm -v: 6.7.0
strapi version: 3.0.0-alpha.25.2
uname -r output: Linux 4.14.106-97.85.amzn2.x86_64
DB: mySQL v2.16
So far I've tried accessing the count() method of User model like aforementioned step3, but my controller doesn't look like the example as I'm working with users-permissions plugin.
This is the action I've tried to edit (located in project/plugins/users-permissions/controllers/User.js)
find: async (ctx) => {
let data = await strapi.plugins['users-permissions'].services.user.fetchAll(ctx.query);
data.reduce((acc, user) => {
acc.push(_.omit(user.toJSON ? user.toJSON() : user, ['password', 'resetPasswordToken']));
return acc;
}, []);
// Send 200 `ok`
ctx.send(data);
},
From what I've gathered on Strapi documentation (here and also here), context is a sort of wrapper object. I only worked with Express-generated APIs before, so I understood this snippet as 'use fetchAll method of the User model object, with ctx.query as an argument', but I had no luck logging this ctx.query. And as I can't log stuff, I'm kinda blocked.
In my exploration, I naively tried to log the full ctx object and work from there:
// Send 200 `ok`
ctx.send(data);
strapi.log.info(ctx.query, ' were query');
strapi.log.info(ctx.request, 'were request');
strapi.log.info(ctx.response, 'were response');
strapi.log.info(ctx.res, 'were res');
strapi.log.info(ctx.req, 'were req');
strapi.log.info(ctx, 'is full context')
},
Unfortunately, I fear I miss something obvious, as it gives me no input at all. Making a fetchAll request from my React app with these console.logs print this in my terminal:
[2019-09-19T12:43:03.409Z] info were query
[2019-09-19T12:43:03.410Z] info were request
[2019-09-19T12:43:03.418Z] info were response
[2019-09-19T12:43:03.419Z] info were res
[2019-09-19T12:43:03.419Z] info were req
[2019-09-19T12:43:03.419Z] info is full context
[2019-09-19T12:43:03.435Z] debug GET /users?_sort=id:DESC&_start=0&_limit=10& (74 ms)
While in my frontend I get the good ol' The Content-Range header is missing in the HTTP Response message I'm trying to solve.
After writing this wall of text I realize the logging issue is separated from my original problem, but if I was able to at least log ctx properly, maybe I'd be able to find the solution myself.
Trying to summarize:
Actual problem is, how do I set my Content-Range properly in my strapi controller ? (partially answered cf. edit 3)
Collateral problem n°1: Can't even log ctx object (cf. edit 2)
Collateral problem n°2: Once I figure out the actual problem, is it feasible to address it dynamically (basically some callback function for index/fetchAll routes, in which the model is a variable, on which I'd call the appropriate count() method, and finally append the result to my response header)? I'm not asking for the code here, just if you think it's feasible and/or know a more elegant way.
Thank you for reading through and excuse me if it was confuse; I wasn't sure which infos would be relevant, so I thought the more the better.
/edit1: forgot to mention, in my controller I also tried to log strapi.plugins['users-permissions'].services.user object to see if it actually has a count() method but got no luck with that either. Also tried the original snippet (Step 3 of aforementioned README), but failed as expected as afaik I don't see the User model being imported anywhere (the only import in User.js being lodash)
/edit2: About the logs, my bad, I just misunderstood the documentation. I now do:
ctx.send(data);
strapi.log.info('ctx should be : ', {ctx});
strapi.log.info('ctx.req = ', {...ctx.req});
strapi.log.info('ctx.res = ', {...ctx.res});
strapi.log.info('ctx.request = ', {...ctx.request});
ctrapi.log.info('ctx.response = ', {...ctx.response});
Ctx logs this way; also it seems that it needs the spread operator to display nested objects ({ctx.req} crash the server, {...ctx.req} is okay). Cool, because it narrows the question to what's interesting.
/edit3: As expected, having logs helps big time. I've managed to display my users (although in the dirty way). Couldn't find any count() method, but watching the data object that is passed to ctx.send(), it's equivalent to your typical 'res.data' i.e a pure JSON with my user list. So a simple .length did the trick:
let data = await strapi.plugins['users-permissions'].services.user.fetchAll(ctx.query);
data.reduce((acc, user) => {
acc.push(_.omit(user.toJSON ? user.toJSON() : user, ['password', 'resetPasswordToken']));
return acc;
}, []);
ctx.set('Content-Range', data.length) // <-- it did the trick
// Send 200 `ok`
ctx.send(data);
Now starting to work on the hard part: the dynamic callback function that will do that for any index/fetchAll call. Will update once I figure it out
I'm using React Admin and Strapi together and installed ra-strapi-provider.
A little boring to paste Content-Range header into all of my controllers, so I searched for a better solution. Then I've found middleware concept and created one that fits my needs. It's probably not the best solution, but do its job well:
const _ = require("lodash");
module.exports = strapi => {
return {
// can also be async
initialize() {
strapi.app.use(async (ctx, next) => {
await next();
if (_.isArray(ctx.response.body))
ctx.set("Content-Range", ctx.response.body.length);
});
}
};
};
I hope it helps
For people still landing on this page:
Strapi has been updated from #alpha to #beta. Care, as some of the code in my OP is no longer valid; also some of their documentation is not up to date.
I failed to find a "clever" way to solve this problem; in the end I copy/pasted the ctx.set('Content-Range', data.length) bit in all relevant controllers and it just worked.
If somebody comes with a clever solution for that problem I'll happily accept his answer. With the current Strapi version I don't think it's doable with policies or lifecycle callbacks.
The "quick & easy fix" is still to customize each relevant Strapi controller.
With strapi#beta you don't have direct access to controller's code: you'll first need to "rewrite" one with the help of this doc. Then add the ctx.set('Content-Range', data.length) bit. Test it properly with RA, so for the other controllers, you'll just have to create the folder, name the file, copy/paste your code + "Search & Replace" on model name.
The "longer & cleaner fix" would be to dive into the react-admin source code and refactorize so the lack of "Content-Range" header doesn't break pagination.
You'll now have to maintain your own react-admin fork, so make sure you're already committed into this library and have A LOT of tables to manage through it (so much that customizing every Strapi controller will be too tedious).
Before forking RA, please remember all the stuff you can do with the Strapi backoffice alone (including embedding your custom React app into it) and ensure it will be worth the trouble.

How to navigate Edge extension local storage callback requirements

I'm trying to access the local storage data in Edge set by my options page, using my popup script. Is there a current, working example of this available?
I was using localStorage, but it would only update the popup if I reloaded the extension after saving changes in my options page. I want to make it easier on the user by allowing the popup to access it immediately after saving, without reloading. I found the browser.storage.local.get(), but documentation conflicts everywhere I look, and I can't find viable working examples.
I have used, per Edge documentation:
browser.storage.local.get("sample");
But it throws an error requiring a callback function. So then I used:
let sample = browser.storage.local.get("example");
sample.then(ifGood, ifBad);
I get an error regarding property "then".
Then I simply tried adding a callback to the action itself:
sample = browser.storage.local.get("example", callbackFunction);
function callbackFunction(data){
alert(data);
}
The end alert should display a string, but it just displays an empty Object. How do I access the data returned in the callback? I tried callbackFunction(this) as an argument in the get, but it throws an error about the syntax of the get.
I found a work-around using browser.runtime.reload() in the Options page when saving the changes. It still reloads the extension, but it does it without requiring the user to do it manually.
You should use this syntax:
browser.storage.local.get(propertyName | null, callbackFn)
where
callbackFn = function fn(resultObject) {...}
When you pass null you will get whole storage object.
Look for example 1 or example 2 in my Edge extension.

Post a text request in Casablanca (C++ REST SDK)

I am writing a client side code in Visual C++ 2012 using C++ Rest SDK (codename "Casablanca").
I have a client created and wish to POST a text string to the server. However, when I send the following code, it is compiling but not sending sending the request.
When I remove everything after "methods::POST" and send a blank post request, then it is sent and received by the server.
Can you please guide me where the problem is. The documentation related to this function is available on Casablanca Documentation.
pplx::task<http_response>resp = client.request(methods::POST,L"",L"This is the random text that I wish to send", L"text/plain");
I think the usage you give here looks correct.
Is your Casablanca the latest version ? Please check that out from here : http://casablanca.codeplex.com/
If you are sure your measurement is accurate, you may want to create a minimal repro and file a bug here : http://casablanca.codeplex.com/workitem/list/basic
I was having a similar problem, all my POSTs was arriving in blank on server , after a few hours work above it, i found a possible solution.
I changed the default content type to application/x-www-form-urlencoded and I started to pass the values like this Example data=text1&data2=text2
client.request(methods::POST,L"",L"data=text1&data2=text2", L"application/x-www-form-urlencoded");
The body parameter must be a json::value.
I cannot comment yet so I have to put my thoughts in an answer. I solved this problem like this: There is an overload of the request method that takes as a parameter the content type so that you do not have to change the code.
m_client->request(methods::POST, L"/statuses/update.json?" + url_encode(data),L"",L"application/x-www-form-urlencoded");
Obviously you would have to implement the url_encode method but that is not difficult. There is a pretty good implementation in "Cassablanca". A search on this site will alos turn up some good examples.

Monotouch/iPhone - Call to HttpWebRequest.GetRequestStream() connects to server when HTTP Method is DELETE

My Scenario:
I am using Monotouch for iOS to create an iPhone app. I am calling ASP.NEt MVC 4 Web API based http services to login/log off. For Login, i use the POST webmethod and all's well. For Logoff, i am calling the Delete web method. I want to pass JSON data (serialized complex data) to the Delete call. If i pass simple data like a single string parameter as part of the URL itself, then all's well i.e. Delete does work! In order to pass the complex Json Data, here's my call (i have adjusted code to make it simple by showing just one parameter - UserName being sent via JSON):
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost/module/api/session/");
req.ContentType = "application/json";
req.CookieContainer = jar;
req.Method = "Delete";
using (var streamWrite = new StreamWriter(req.GetRequestStream()))
{
string jSON = "{\"UserName\":\"" + "someone" + "\"}";
streamWrite.Write(jSON);
streamWrite.Close();
}
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
on the server, the Delete method looks has this definition:
public void Delete(Credentials user)
where Credentials is a complex type.
Now, here's the issue!
The above code, gets into the Delete method on the server as soon as it hits:
req.GetRequestStream()
And hence the parameter sent to the Delete method ends up being null
And here's the weird part:
If i use the exact same code using a test VS 2010 windows application, even the above code works...i.e it does not call Delete until req.GetResponse() is called! And in this scenario, the parameter to the Delete method is a valid object!
QUESTION
Any ideas or Is this a bug with Monotouch, if so, any workaround?
NOTE:
if i change the Delete definition to public void Delete(string userName)
and instead of json, if i pass the parameter as part of the url itself, all's well. But like i said this is just a simplified example to illustrate my issue. Any help is appreciated!!!
This seems to be ill-defined. See this question for more details: Is an entity body allowed for an HTTP DELETE request?
In general MonoTouch (based on Mono) will try to be feature/bug compatible with the Microsoft .NET framework to ease code portability between platforms.
IOW if MS.NET ignores the body of a DELETE method then so will MonoTouch. If the behaviour differs then a bug report should be filled at http://bugzilla.xamarin.com

Resources