Fetch ID value from given JSON - regex

How can I get the value of id from given sample below..
{ "photoId": { "id": "CAoSLEFGMVFpcE5tbW82VTNhZ210ZDlLQ0J4dTEtNk5nZlNTV25CeXhzTHJxZ3Rk" } }
I am getting this value from
$response_meta = curl_exec($curl_meta);
I want the result
CAoSLEFGMVFpcE5tbW82VTNhZ210ZDlLQ0J4dTEtNk5nZlNTV25CeXhzTHJxZ3Rk
and store in avriable.

You will be able to access it the following way.
$response_meta['photoID']['id']

Just use the $response_meta.photoId.id or $response_meta['photoId']['id']
var $response_meta = { "photoId": { "id": "CAoSLEFGMVFpcE5tbW82VTNhZ210ZDlLQ0J4dTEtNk5nZlNTV25CeXhzTHJxZ3Rk" } };
console.log($response_meta.photoId.id);
console.log($response_meta['photoId']['id']);
Here is a plunker: Get the id from the object

I did by this way
first set
CURLOPT_RETURNTRANSFER => true,
$response_meta = curl_exec($curl_meta);
$response_json = json_decode($response_meta, true);
$response_result = var_dump($response_json['photoId']['id']);
It gave me the result
string(64) "CAoSLEFGMVFpcE9pNkhOUmI0X2ZSQTJaUkM0ZFVMa1U4Q25hWEUwbEtKY3VGNm9J"

Related

AdonisJS exists Validator

I'm following the official [documentation] (https://legacy.adonisjs.com/docs/4.0/validator) && indicative, but I couldn't find anything to help me.
I want to validate if the given param exists on database.
So I tried:
app/Validators/myValidator
const { rule } = use('Validator')
get rules () {
return {
userId: 'required|integer|exists:MyDatabase.users,userId', <-- this is what isn't working
date: [
rule('date'),
rule('dateFormat', 'YYYY-MM-DD')
]
}
}
// Getting the data to be validated
get data () {
const params = this.ctx.params
const { userId, date } = params
return Object.assign({}, { userId }, { date })
}
It gives me the following error:
{
"error": {
"message": "select * from `MyDatabase`.`users`.`userId` where `undefined` = '2' limit 1 - ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.`userId` where `undefined` = '2' limit 1' at line 1",
"name": "ErrorValidator",
"status": 40
}
}
How should I properly indicate that I want to compare MyDatabase.users.userid to the given parameter?
After a few hard try/error I stumbled upon the solution.
Just need to follow what is inside hooks.js and pass the values separated by comma, like so:
get rules () {
return {
userId: 'required|integer|exists:MyDatabase,MyTable,columntoCompare',
}
}

how to get data from {} in graphql

I want to get data about user addinfo(bool value).
when i do console.log(data.user), i can get data.user referred to below picture.
if when i do console.log(data.user.user), it shows that user is undefined referred to below picture.
{
user(token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImI3ZTA5YmVhOTAzNzQ3ODQiLCJleHAiOjE1NjM4OTcxNzksIm9yaWdJYXQiOjE1NjM4OTY4Nzl9.QFB58dAvqIC9RBBohN1b3TdR542dBZEcXOG1MSTqAQQ") {
user {
id
addinfo
}
}
}
this code show that
{
"data": {
"user": {
"user": {
"id": "4",
"addinfo": false
}
}
}
}
I can't see the rest of your code, but if the code is fetching your users, there is a time before the request comes back where your user has not been fetched yet. It looks like your screenshot shows this. There is an undefined before the successful object.
You need to ensure that the data has come back first be checking if the data prop is truthy or some other way to check if the promise has completed yet.
ie
if (!data.user) return 'Loading...';
return (
<Switch>
...
In GraphQL I'm getting user info using e.g. below code:
async getUser(id) {
const result = await this.api.query({
query: gql(getUser),
variables: {
id,
},
});
return result.data.getUser || null;
}
I'm invoking it by:
const user = await userService.getUser(id);
and I do have access to user properties.
Maybe you're trying to get user data before they are retrieved and available?

How do you find an item in a repository by something other than id

If I have a repository with many properties and I want to find something by the non-id property, do I just find all and then return the data after a boolean comparison, or is there a better way to find by a property that's not the ID?
In loopback4, you need to use repository for this purpose. Do as below.
For case where you know there will be just one entry with value. (Unique columns)
const user = await this.userRepository.findOne({
where: {
username: 'test_admin'
}
});
For case where there can be multiple.
const user = await this.userRepository.find({
where: {
firstName: 'test admin'
}
});
For Loopback 3, here you find the documentation for querying data: https://loopback.io/doc/en/lb3/Querying-data.html
Basically, use a query filter like this:
const objects = await app.models.ModelName.find(
{
where: {
propertyName: value
}
}
)
Don't forget to define an index for the property you want to query because otherwise, the database engine will perform a full table scan.
"properties": {
"propertyName": {
"type": "string",
"index": {
"unique": true
}
},
...
}

postman: save response on a global variable

With PostMan, how can save the follow response:
[
{
"id": "6254c754-5a97-43fd-9b48-c428b9bd69e5",
"name": "fdsfds",
"description": "fdzf",
"type": 0,
"createDate": "2018-08-01T17:49:29.071+01:00",
"lastUpdateDate": "2018-08-01T17:49:29.071+01:00",
"lastUpdateUser": null,
"variables": null,
"instructions": null
}
]
on a variable? For example the id?
var jsonData = pm.response.json();
console.log(jsonData.id);
pm.globals.set("variable_key", jsonData.id);
to set the environment variable "authkey" from response
var obj = pm.response.json()["token"];
pm.environment.set("authkey", obj);
You can't save JS Objects directly in a global variable but you can use JSON library to convert your object to string and save, like the following code:
// create the JS Object
var obj = {
foo: "bar",
some_number: 91
}
// convert the obj to string and save in the globals
pm.globals.set("my_obj", JSON.stringify(obj));
// get obj from globals and parse to JS Object again
var obj_from_globals = JSON.parse(pm.globals.get("my_obj"));
// print int he console
console.log(obj_from_globals);
You should expect this in your console:
I think i resolve this with:
var jsonData = pm.response.json();
for (var key in jsonData) {
if (jsonData.hasOwnProperty(key)) {
var seqDelete = jsonData[key].id;
console.log(seqDelete);
}
}
pm.globals.set("seqDelete", seqDelete);
This isn´t totally correct.
If i have multidimension array, this only gets one ID value
This is the response that I work with:
{id: "myId", version: "2.0", name: "test"…}
This is how I set the id value from the response into my global variable "appId":
var requestJson = JSON.parse(request.data);
console.log(requestJson)
postman.setGlobalVariable("appId", requestJson.id);
Result:

What's the best way to build an aggregate document in couchdb?

Alright SO users. I am trying to learn and use CouchDB. I have the StackExchange data export loaded as document per row from the XML file, so the documents in couch look basically like this:
//This is a representation of a question:
{
"Id" : "1",
"PostTypeId" : "1",
"Body" : "..."
}
//This is a representation of an answer
{
"Id" : "1234",
"ParentId" : "1",
"PostTypeId" : "2"
"Body" : "..."
}
(Please ignore the fact that the import of these documents basically treated all the attributes as text, I understand that using real numbers, bools, etc. could yield better space/processing efficiency.)
What I'd like to do is to map this into a single aggregate document:
Here's my map:
function(doc) {
if(doc.PostTypeId === "2"){
emit(doc.ParentId, doc);
}
else{
emit(doc.Id, doc);
}
}
And here's the reduce:
function(keys, values, rereduce){
var retval = {question: null, answers : []};
if(rereduce){
for(var i in values){
var current = values[i];
retval.answers = retval.answers.concat(current.answers);
if(retval.question === null && current.question !== null){
retval.question = current.question;
}
}
}
else{
for(var i in values){
var current = values[i];
if(current.PostTypeId === "2"){
retval.push(current);
}
else{
retval.question = current;
}
}
}
return retval;
}
Theoretically, this would yield a document like this:
{
"question" : {...},
"answers" : [answer1, answer2, answer3]
}
But instead I am getting the standard "does not reduce fast enough" error.
Am I using Map-Reduce incorrectly, is there a well-established pattern for how to accomplish this in CouchDb?
(Please also note that I would like a response with the complete documents, where the question is the "parent" and the answers are the "children", not just the Ids.)
So, the "right" way to accomplish what I'm trying to do above is to add a "list" as part of my design document. (and the end I am trying to achieve appears to be referred to as "collating documents").
At any rate, you can configure your map however you like, and combine it with an a "list" in the same function.
To solve the above question, I eliminated my reduce (only have a map function), and then added a function like the following:
{
"_id": "_design/posts",
"_rev": "11-8103b7f3bd2552a19704710058113b32",
"language": "javascript",
"views": {
"by_question_id": {
"map": "function(doc) {
if(doc.PostTypeId === \"2\"){
emit(doc.ParentId, doc);
}
else{
emit(doc.Id, doc);
}
}"
}
},
"lists": {
"aggregated": "function(head, req){
start({\"headers\": {\"Content-Type\": \"text/json\"}});
var currentRow = null;
var currentObj = null;
var retval = [];
while(currentRow = getRow()){
if(currentObj === null || currentRow.key !== currentObj.key){
currentObj = {key: currentRow.key, question : null, answers : []};
retval.push(currentObj);
}
if(currentRow.value.PostTypeId === \"2\"){
currentObj.answers.push(currentRow.value);
}
else{
currentObj.question = currentRow.value;
}
}
send(toJSON(retval));
}"
}
}
So, after you have some elements loaded up, you can access them like so:
http://localhost:5984/<db>/_design/posts/_list/aggregated/by_question_id?<standard view limiters>
I hope this saves people some time.