How to restrict returned Wordpress REST-API fields when using WP-API Node Module - wordpress-rest-api

If I call this Wordpress blog url in a browser
<root...>wp-json/wp/v2/posts?per_page=5&fields=id,link,title
I get back JSON and the result is restricted to 3 fields
So how can I do this when using the node js wp-api module?
I would like something similar to .fields([]) but there is nothing in the docs, can find nothing in the module code.
TypeError: wpapi.posts(...).perPage(...).fields is not a function
Or something like .filter({})
TypeError: wpapi.posts(...).perPage(...).filter is not a function
But I think this might be connected with another Wordpress plugin that's required.
wpapi.posts()
.perPage(5)
.fields(['id','link','title'])
.search( 'search-term' ) //= (search in title or content)
.filter({
category_name: 'islands',
fields: [ 'id','link','title' ]
})
.get(function (err, data) {
..... etc.
TypeError: wpapi.posts(...).perPage(...).fields is not a function
Can anyone point me in the right direction? Thanks

It appears wp-api node module does not allow this.
So I uninstalled it and am now using axios along with standard text urls.

This worked for me:
wpapi.posts().param('_fields', 'id,title,content').get()
The node-wpapi documentation seems to suggest say that perPage() and functions like it are convenience functions that call param(props, value).
wpapi.posts().param('_fields', ['id','title','content']).get()
also seems to work but the first option gives a resulting request url that looks more like the format the Wordpress REST API Handbook uses

Related

Working with URL parameters in custom Kibana plugin

I am working on a custom plugin to Kibana (7.5.2). The plugin is of type 'app'. I would like to be able to pass parameters to this plugin in order to pre-load some data from Elasticsearch. I.e., I need to provide users with some specific URLs containing parameters that will be used by the plugin to show only a relevant portion of data.
My problem is that I was not able to find sufficient documentation on this and I do not know what the correct approach should be. I will try to summarize what I know/have done so far:
I have read the official resources on plugin development
I am aware of the fact that _g and _a URL parameters are used to pass state in Kibana applications. However, a) I am not sure if this is the correct approach in my case and b) I also failed to find any information on how my plugin should access the data from these parameters.
I checked the sources of other known plugins, but again, failed to find any clues.
I am able to inject some configuration values using injectUiAppVars in the init method of my plugin (index.js) and retrieve these values in my app (main.js):
index.js:
export default function (kibana) {
return new kibana.Plugin({
require: ['elasticsearch'],
name: ...,
uiExports: {
...
},
...
init(server, options) { // eslint-disable-line no-unused-vars
server.injectUiAppVars('logviewer', async () => {
var kibana_vars = await server.getInjectedUiAppVars('kibana');
var aggregated_vars = { ...kibana_vars, ...{ mycustomparameter: "some value" } }
return aggregated_vars
});
...
}
});
}
main.js
import chrome from 'ui/chrome';
. . .
const mycustomparameter = chrome.getInjected('mycustomparameter');
Providing that I manage to obtain parameters from URL, this would allow me to pass them to my app (via mycustomparameter), but again, I am not sure if this approach is correct.
I tried to get some help via the Elastic forum, but did not receive any answer yet.
My questions
1. Is there any source of information on this particular topic? I am aware of the fact that the plugin API changes frequently, hence I do not expect to find an extensive documentation. Maybe a good example?
Am I completely off course with the way I am trying to achieve it?
Thanks for reading this, any help would be much appreciated!

CakePHP Custom REST Routes

I'm using CakePHP and Backbone.js as a frontend so I want to get CakePHP's REST routing working, but I don't really want to use the default REST routes.
For example, I want to be able to POST to http://example.com/cards/search.json and get a list of results in JSON, however I am getting a 200 status code back, and a blank response which makes me think the routing is not working properly.
I have tested my code using the default REST routes by chagning the search() method of my controller to add(), but I would prefer to be able to properly setup and use custom REST routes.
Router::connect(
"/cards/search",
array(
"[method]" => "POST",
"controller" => "cards",
"action" => "search"
)
);
Router::mapResources('cards');
Router::parseExtensions('json');
The code from my routes.php is above and I'm not entirely sure why it isn't working...either because the documentation on this is a little light, or I just don't understand routing very well.
You can get the json output in this url:
http://localhost:{port}/{api* name in config # app/core}/{controller name}/{things after api_ in function name}/{input parameters}.json
read more in here
You may have to alter the routing to change the name
api
to anything in
Configure::write('Routing.prefixes', array('master', 'api'));
in core.php in app/config
Feel free for a comment and also share your core.php in config for more explanation.

I'd like to know how to change pages in Form Post

I'd like to know how to change pages by putting some in Forms by Post way.
http://www.aldoshoes.com/us/women/shoes/flats
in this page
How do I move to page 2 by putting some variabels in URL?
Please help me out.
This is not possible because it seems to me that the server does not handle GET parameters in the http request.
However it is possible to achieve this using POST parameters, either programmatically or using a plug-in for Chrome/Firefox (see Super User question).
The server accepts the following parameters:
formAction:
startRow:1
rowsperPage:12
flagID:
seasonID:
dimensionID:
sizeID:
colorID:
colorGroupID:
itemCategoryLevel1:1100
itemCategoryLevel2:1101
itemCategoryLevel3:1120
itemCategoryLevel4:
styleID:
styleDescription:
keywords:
alternateDescription:
descriptionDetail1:
descriptionDetail2:
descriptionDetail3:
onsale:N
sortBy:
itemFamilyID:
heelHeight:
To get to the second page of the shop you can set the parameter startRow to 13:
startRow:13
rowsperPage:12

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

I've implemented a REST/CRUD backend by following this article as an example: http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/ . I have MongoDB running locally, I'm not using MongoLabs.
I've followed the Google tutorial that uses ngResource and a Factory pattern and I have query (GET all items), get an item (GET), create an item (POST), and delete an item (DELETE) working. I'm having difficulty implementing PUT the way the backend API wants it -- a PUT to a URL that includes the id (.../foo/) and also includes the updated data.
I have this bit of code to define my services:
angular.module('realmenServices', ['ngResource']).
factory('RealMen', function($resource){
return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method:'PUT'},
remove: {method:'DELETE'}
});
I call the method from this controller code:
$scope.change = function() {
RealMen.update({entryId: $scope.entryId}, function() {
$location.path('/');
});
}
but when I call the update function, the URL does not include the ID value: it's only "/realmen", not "/realmen/ID".
I've tried various solutions involving adding a "RealMen.prototype.update", but still cannot get the entryId to show up on the URL. (It also looks like I'll have to build the JSON holding just the DB field values myself -- the POST operation does it for me automatically when creating a new entry, but there doesn't seem to be a data structure that only contains the field values when I'm viewing/editing a single entry).
Is there an example client app that uses all four verbs in the expected RESTful way?
I've also seen references to Restangular and another solution that overrides $save so that it can issue either a POST or PUT (http://kirkbushell.me/angular-js-using-ng-resource-in-a-more-restful-manner/). This technology seems to be changing so rapidly that there doesn't seem to be a good reference solution that folks can use as an example.
I'm the creator of Restangular.
You can take a look at this CRUD example to see how you can PUT/POST/GET elements without all that URL configuration and $resource configuration that you need to do. Besides it, you can then use nested resources without any configuration :).
Check out this plunkr example:
http://plnkr.co/edit/d6yDka?p=preview
You could also see the README and check the documentation here https://github.com/mgonto/restangular
If you need some feature that's not there, just create an issue. I usually add features asked within a week, as I also use this library for all my AngularJS projects :)
Hope it helps!
Because your update uses PUT method, {entryId: $scope.entryId} is considered as data, to tell angular generate from the PUT data, you need to add params: {entryId: '#entryId'} when you define your update, which means
return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method:'PUT', params: {entryId: '#entryId'}},
remove: {method:'DELETE'}
});
Fix: Was missing a closing curly brace on the update line.
You can implement this way
$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '#entryId'}, {
UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
})
RealMen.query() //GET /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1
//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1
//query string
RealMen.query({name:'john'}) //GET /realmen?name=john
Documentation:
https://docs.angularjs.org/api/ngResource/service/$resource
Hope it helps

How to post a file in grails

I am trying to use HTTP to POST a file to an outside API from within a grails service. I've installed the rest plugin and I'm using code like the following:
def theFile = new File("/tmp/blah.txt")
def postBody = [myFile: theFile, foo:'bar']
withHttp(uri: "http://picard:8080/breeze/project/acceptFile") {
def html = post(body: postBody, requestContentType: URLENC)
}
The post works, however, the 'myFile' param appears to be a string rather than an actual file. I have not had any success trying to google for things like "how to post a file in grails" since most of the results end up dealing with handling an uploaded file from a form.
I think I'm using the right requestContentType, but I might have missed something in the documentation.
POSTing a file is not as simple as what you have included in your question (sadly). Also, it depends on what the API you are calling is expecting, e.g. some API expect files as base64 encoded text, while others accept them as mime-multipart.
Since you are using the rest plugin, as far as I can recall it uses the Apache HttpClient, I think this link should provide enough info to get you started (assuming you are dealing with mime-multipart). It shouldn't be too hard to change it around to work with your API and perhaps make it a bit 'groovy-ier'