json server is up and running..API response from Browser GET request is working fine.. but from fetch i always got error "Network Request Failed" ... this code is for react-native on expo environment
i also tried by replacing localhost with corresponding ip.. still didn't work for me.. where am i getting stucked?
#base url
export const baseUrl = "http://localhost:3002/";
fetchPosts reducer
return fetch(baseUrl + "posts")
.then(
(response) => {
if (response.ok) {
return response;
} else {
var error = new Error(
"Error " + response.status + ": " + response.statusText
);
error.response = response;
throw error;
}
},
(error) => {
var errmess = new Error(error.message);
throw errmess;
}
)
.then((response) => response.json())
.then((posts) => dispatch(addPosts(posts)))
.catch((error) => dispatch(postsFailed(error.message)));
logger output in console
action POSTS_LOADING # 17:09:00.842
prev state Object {
"highlights": Object {
"errMess": null,
"highlights": Array [],
"isLoading": true,
},
"posts": Object {
"errMess": "Network request failed",
"isLoading": false,
"posts": Array [],
},
}
action Object {
"type": "POSTS_LOADING",
}
next state Object {
"highlights": Object {
"errMess": null,
"highlights": Array [],
"isLoading": true,
},
"posts": Object {
"errMess": null,
"isLoading": true,
"posts": Array [],
},
}
action POSTS_FAILED # 17:09:00.928
prev state Object {
"highlights": Object {
"errMess": null,
"highlights": Array [],
"isLoading": true,
},
"posts": Object {
"errMess": null,
"isLoading": true,
"posts": Array [],
},
}
action Object {
"payload": "Network request failed",
"type": "POSTS_FAILED",
}
next state Object {
"highlights": Object {
"errMess": null,
"highlights": Array [],
"isLoading": true,
},
"posts": Object {
"errMess": "Network request failed",
"isLoading": false,
"posts": Array [],
},
}
Related
I want to get the response.data (JSON Object) with value only in the new object on update form i.e. I want to filter it on computed/created on vue 3 - the json object received from API. My backend is Laravel 8 resource API.
On EditPatient.vue - The vue js is
export default {
data() {
return {
patient: {},
}
},
created() {
this.$axios.get('/sanctum/csrf-cookie').then(response => {
this.$axios.get(`/api/patients/${this.$route.params.id}`)
.then(response => {
this.patient = response.data // JSON object
/* .filter(function(item) {
item !== null || item !=='';
}) */ // this didn't work.
//I want to response.data and apply to this.patient object.
})
.catch(function (error) {
console.error(error);
});
})
},
}
response.data is
{ "created_by": 1, "firstname": "Kamal", "lastname": "", "sex": "M", "address": "Kathmandu, Bagmati, Nepal", "education": "Yes", "grade": "MSc", "alcohol": null, "alcohol_type": null, "weight": "", "kidney_disease": null, "high_bp": "No", "diabetes": null, "heart_attack_stroke": "No", "present_diabetes": "No", "systolic": "", "pulse_rate": "" }
On laravel api, I got a patient row as follow:
public function show($id)
{
$patient = Patient::find($id);
return response()->json($patient); // send data in json ojbect for frontend
}
It is better, If I can apply on backend too. Get the columns of single row which has value only.
To get only the object properties that are not empty/null:
Use Object.entries() on the response.data object to get an array of key/value pairs.
Use Array.prototype.filter() on the result, filtering out empty string and null.
Use Object.fromEntries() on the filtered result to create an object.
const input = { "created_by": 1, "firstname": "Kamal", "lastname": "", "sex": "M", "address": "Kathmandu, Bagmati, Nepal", "education": "Yes", "grade": "MSc", "alcohol": null, "alcohol_type": null, "weight": "", "kidney_disease": null, "high_bp": "No", "diabetes": null, "heart_attack_stroke": "No", "present_diabetes": "No", "systolic": "", "pulse_rate": "" }
const entries = Object.entries(input) // 1️⃣
const nonEmptyOrNull = entries.filter(([key,val]) => val !== '' && val !== null) // 2️⃣
const output = Object.fromEntries(nonEmptyOrNull) // 3️⃣
console.log(output)
I'm creating an app in React-native and I use expo-SQLite for the database.
Unfortunately, I have a problem in my db request and I don't understand the error sent from sqlite.
Could you please help me ?
This is my code:
db.transaction(tx => {
tx.executeSql(
`create table if not exists Espace (id_espace integer primary key autoincrement,name text not null unique)`, [], (tx, results) => {
console.log("Create table Espace");
}
);
});
db.transaction(tx => {
tx.executeSql(
`INSERT INTO Indicator (title, display_order, type, hidden, graphic_type, id_espace) VALUES ('?','?','?','?','?','?')`, [title,display_order,type, hidden, graphic_type, espace], (_, {rows}) =>{
console.log('Put Indicator: ' + title + type + display_order + hidden + graphic_type + espace);
},
(error)=>{
console.log(error);
return true;
}
);
});
When I try to create an indicator my console display this error from sqlite:
WebSQLTransaction {
"_complete": false,
"_error": null,
"_running": true,
"_runningTimeout": false,
"_sqlQueue": Queue {
"first": undefined,
"last": undefined,
"length": 0,
},
"_websqlDatabase": WebSQLDatabase {
"_currentTask": TransactionTask {
"errorCallback": [Function anonymous],
"readOnly": false,
"successCallback": [Function anonymous],
"txnCallback": [Function anonymous],
},
"_db": SQLiteDatabase {
"_closed": false,
"_name": "diplea.db",
},
"_running": true,
"_txnQueue": Queue {
"first": Object {
"item": TransactionTask {
"errorCallback": [Function anonymous],
"readOnly": false,
"successCallback": [Function anonymous],
"txnCallback": [Function anonymous],
},
},
"last": Object {
"item": TransactionTask {
"errorCallback": [Function anonymous],
"readOnly": false,
"successCallback": [Function anonymous],
"txnCallback": [Function anonymous],
},
},
"length": 1,
},
"exec": [Function anonymous],
"version": "1.0",
}
It means nothing to me ... could you tell me a way to understand it? Or maybe what is wrong in my code ...
Thanks in advance !
What you are seeing is the Transaction itself, not the error.
According to Expo's SQLite docs, the error callback of Transaction.executeSql takes two arguments:
error (function) -- Called if an error occured executing this particular query in the transaction. Takes two parameters: the transaction itself, and the error object.
You want your error callback to look like this:
tx.executeSql(
...,
...,
...,
(_, error) => {
console.log(error);
return true;
}
);
I am using Couchdb server running in a Docker Build on my Mac.
To access the Data I run an express app via node.
After Building my Schema for the Graphql and test it with the Graphql Interface, I am able to get the Data from a specific User but not the Document for all the Users from my users resolver.
Here is my Code:
//resolvers
var resolvers = {
users: () => {
var statement = "SELECT META(user).id, user.* FROM `" + bucket._name + "` AS user WHERE user.type = 'user'";
var query = Couchbase.N1qlQuery.fromString(statement);
return new Promise((resolve, reject) => {
bucket.query(query, (error, result) => {
if(error) {
return reject(error);
}
resolve(result);
});
});
},
user: (data) => {
var id = data.id;
return new Promise((resolve, reject) => {
bucket.get(id, (error, result) => {
if (error) {
return reject(error);
}
resolve(result.value);
});
});
}
};
//express setup
app.use("/graphql", ExpressGraphQL({
schema: schema,
rootValue: resolvers,
graphiql: true
}));
app.listen(3000, () => {
console.log("lisntening...")
});
//Schema
var schema = BuildSchema(`
type Query{
user(id: String!): User,
users: [User]
}
type User{
id: String,
profileImage: String,
birthdate: String,
reviews: [String],
premium: Boolean
}
`);
When I try my query like this:
{
users{
id
}
}
i get the following error msg returned:
{
"errors": [
{
"message": "syntax error - at user",
"locations": [
{
"line": 31,
"column": 3
}
],
"path": [
"users"
]
}
],
"data": {
"users": null
}
}
The specific user query from the second resolver works fine!
Here my test document in the Database:
{
"id": "ohuibjnklmönaio",
"profileImage": "pic",
"birthdate": "date",
"reviews": [
"a",
"b"
],
"premium": true,
"type": "user"
}
I've been having troubles with Elastic Search (ES) dynamic mappings. Seems like I'm in a catch-22. https://www.elastic.co/guide/en/elasticsearch/guide/current/custom-dynamic-mapping.html
The main goal is to store everything as a string that comes into ES.
What I've tried:
In ES you can't create a dynamic mapping until the index has been
created. Okay, makes sense.
I can't create an empty index, so if
the first item sent into the index is not a string, I can't
re-assign it... I won't know what type of object with be the first
item in the index, it could be any type, due to how the the app accepts a variety of objects/events.
So if I can't create the mapping ahead of time, and I can't insert an empty index to create the mapping, and I can't change the mapping after the fact, how do I deal with the first item if its NOT a string???
Here's what I'm currently doing (using the Javascript Client).
createESIndex = function (esClient){
esClient.index({
index: 'timeline-2015-11-21',
type: 'event',
body: event
},function (error, response) {
if (error) {
logger.log(logger.SEVERITY.ERROR, 'acceptEvent elasticsearch create failed with: '+ error + " req:" + JSON.stringify(event));
console.log(logger.SEVERITY.ERROR, 'acceptEvent elasticsearch create failed with: '+ error + " req:" + JSON.stringify(event));
res.status(500).send('Error saving document');
} else {
res.status(200).send('Accepted');
}
});
}
esClientLookup.getClient( function(esClient) {
esClient.indices.putTemplate({
name: "timeline-mapping-template",
body:{
"template": "timeline-*",
"mappings": {
"event": {
"dynamic_templates": [
{ "timestamp-only": {
"match": "#timestamp",
"match_mapping_type": "date",
"mapping": {
"type": "date",
}
}},
{ "all-others": {
"match": "*",
"match_mapping_type": "string",
"mapping": {
"type": "string",
}
}
}
]
}
}
}
}).then(function(res){
console.log("put template response: " + JSON.stringify(res));
createESIndex(esClient);
}, function(error){
console.log(error);
res.status(500).send('Error saving document');
});
});
Index templates to the rescue !! That's exactly what you need, the idea is to create a template of your index and as soon as you wish to store a document in that index, ES will create it for you with the mapping you gave (even dynamic ones)
curl -XPUT localhost:9200/_template/my_template -d '{
"template": "index_name_*",
"settings": {
"number_of_shards": 1
},
"mappings": {
"type_name": {
"dynamic_templates": [
{
"strings": {
"match": "*",
"match_mapping_type": "*",
"mapping": {
"type": "string"
}
}
}
],
"properties": {}
}
}
}'
Then when you index anything in an index whose name matches index_name_*, the index will be created with the dynamic mapping above.
For instance:
curl -XPUT localhost:9200/index_name_1/type_name/1 -d '{
"one": 1,
"two": "two",
"three": true
}'
That will create a new index called index_name_1 with a mapping type for type_name where all properties are string. You can verify that with
curl -XGET localhost:9200/index_name_1/_mapping/type_name
Response:
{
"index_name_1" : {
"mappings" : {
"type_name" : {
"dynamic_templates" : [ {
"strings" : {
"mapping" : {
"type" : "string"
},
"match" : "*",
"match_mapping_type" : "*"
}
} ],
"properties" : {
"one" : {
"type" : "string"
},
"three" : {
"type" : "string"
},
"two" : {
"type" : "string"
}
}
}
}
}
}
Note that if you're willing to do this via the Javascript API, you can use the indices.putTemplate call.
export const user = {
email: {
type: 'text',
},
};
export const activity = {
date: {
type: 'text',
},
};
export const common = {
name: {
type: 'text',
},
};
import { Client } from '#elastic/elasticsearch';
import { user } from './user';
import { activity } from './activity';
import { common } from './common';
export class UserDataFactory {
private schema = {
...user,
...activity,
...common,
relation_type: {
type: 'join',
eager_global_ordinals: true,
relations: {
parent: ['activity'],
},
},
};
constructor(private client: Client) {
Object.setPrototypeOf(this, UserDataFactory.prototype);
}
async create() {
const settings = {
settings: {
analysis: {
normalizer: {
useLowercase: {
filter: ['lowercase'],
},
},
},
},
mappings: {
properties: this.schema,
},
};
const { body } = await this.client.indices.exists({
index: ElasticIndex.UserDataFactory,
});
await Promise.all([
await (async (client) => {
await new Promise(async function (resolve, reject) {
if (!body) {
await client.indices.create({
index: ElasticIndex.UserDataFactory,
});
}
resolve({ body });
});
})(this.client),
]);
await this.client.indices.close({ index: ElasticIndex.UserDataFactory });
await this.client.indices.putSettings({
index: ElasticIndex.UserDataFactory,
body: settings,
});
await this.client.indices.open({
index: ElasticIndex.UserDataFactory,
});
await this.client.indices.putMapping({
index: ElasticIndex.UserDataFactory,
body: {
dynamic: 'strict',
properties: {
...this.schema,
},
},
});
}
}
wrapper.ts
class ElasticWrapper {
private _client: Client = new Client({
node: process.env.elasticsearch_node,
auth: {
username: 'elastic',
password: process.env.elasticsearch_password || 'changeme',
},
ssl: {
ca: process.env.elasticsearch_certificate,
rejectUnauthorized: false,
},
});
get client() {
return this._client;
}
}
export const elasticWrapper = new ElasticWrapper();
index.ts
new UserDataFactory(elasticWrapper.client).create();
This is my code in backend controller in MEAN JS:
exports.list = function(req, res) {
// configure the filter using req params
var filters = {
filters : {
optional : {
contains : req.query.filter
}
}
};
var sort = {
asc : {
desc: 'name'
}
};
Province
.find()
.filter(filters)
.order(sort)
.exec(function (err, provinces) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(provinces);
}
});
};
The request:
http://localhost:3000/provinces?filter[name]=provincia de Barcelona
Returns a filtered result, as expected:
[
{
"_id": "54ba72903f51d73c4aff6da6",
"community": "54ba689f5fdfbdea292b8737",
"location": "{lat: '41.386290', lng: '2.184988', zoom: '11'}",
"__v": 0,
"name": "provincia de Barcelona"
}
]
When I use a different attribute, the filter stops working. Example:
http://localhost:3000/provinces?filters[community]=54ba69755fdfbdea292b8738
Return this:
{
"message": ""
}
And console.log(err) return this:
[CastError: Cast to ObjectId failed for value "/54ba689f5fdfbdea292b8737/i" at path "community"]
message: 'Cast to ObjectId failed for value "/54ba689f5fdfbdea292b8737/i" at path "community"',
name: 'CastError',
type: 'ObjectId',
value: /54ba689f5fdfbdea292b8737/i,
path: 'community' }
The original document:
[
{
"_id": "54ba72903f51d73c4aff6da6",
"community": "54ba689f5fdfbdea292b8737",
"location": "{lat: '41.386290', lng: '2.184988', zoom: '11'}",
"__v": 0,
"name": "provincia de Barcelona"
},
{
"_id": "54ba73c33f51d73c4aff6da7",
"community": "54ba69755fdfbdea292b8738",
"location": "{lat: '42.4298846', lng: '-8.644620199999963', zoom: '11'}",
"__v": 0,
"name": "provincia de Pontevedra"
}
]
Maybe is not the best way, but works :)
exports.list = function(req, res) {
var community = {community: ''};
community.community = mongoose.Types.ObjectId(req.query.filter.community);
console.log(community);
var filters = {
filters : {
optional : {
contains : community
}
}
};
var sort = {
asc : {
desc: 'name'
}
};
Province
.find()
.filter(filters)
.order(sort)
.exec(function (err, provinces) {
console.log(err);
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(provinces);
}
});
};
The request:
http://localhost:3000/provinces?filter[community]=54ba689f5fdfbdea292b8737
The result:
[
{
"_id": "54ba72903f51d73c4aff6da6",
"community": "54ba689f5fdfbdea292b8737",
"location": "{lat: '41.386290', lng: '2.184988', zoom: '11'}",
"__v": 0,
"name": "provincia de Barcelona"
}
]