Custom id generation for Redis-OM nodejs using provided entity data - redis

for example:
const fooSchema = new Schema(Foo, {
userId: { type: 'number' },
channelId: { type: 'number' }
}, {
idStrategy: () => `${userId}${channelId}`
});
Is it possible to provide the idStrategy function with the entity data?

Related

Vue store and computed doesnot reactive even with vue set

I have following computed property in my Vue component:
computed: {
contragent_id: {
get() {
return appData.getters["basket/contragent_id"];
},
set(value) {
return value;
},
},
settings: {
get() {
return appData.getters["basket/delivery_settings"];
},
set(value) {
return value;
},
},
presets: {
get() {
return appData.getters["basket/delivery_presets"];
},
set(value) {
return value;
},
},
},
And i have the Vuex store module :
const moduleBasket = {
namespaced: true,
state: () => ({
presets: {
contragents: [],
partners: {},
delivery: {
types: {},
methods: {},
tc_methods: {},
tc_list: {},
addresses: [],
},
},
summary: {
delivery: {
delivery_type: "",
delivery_method: "",
delivery_tc: "",
delivery_tc_method: "",
delivery_tc_city: "",
delivery_address_id: "",
},
payment: {
method: "",
methodText: "",
},
address: {},
comment: "",
partner_id: "",
contragent_id: "",
price: {
total: "",
nds: "",
delivery: "",
discount: "",
},
fillial: {
address: "",
},
},
}),
mutations: {
changeFillial(state, fillial) {
Vue.set(state.summary, "fillial", fillial);
},
changePartnerId(state, partner_id) {
Vue.set(state.summary, "partner_id", partner_id);
},
changeContragentId(state, contragent_id) {
Vue.set(state.summary, "contragent_id", contragent_id);
// state.summary.contragent_id = contragent_id;
},
changeContragents(state, contragnets) {
Vue.set(state.presets, "contragents", contragnets);
// state.presets.contragents = contragnets;
},
changePartners(state, partners) {
Vue.set(state.presets, "partners", partners);
// state.presets.partners = partners;
},
changeDeliveryPresets(state, presets) {
// console.log('changeDeliveryPresets');
Vue.set(state.presets, "delivery", presets);
// state.presets.delivery = presets;
},
changeDeliveryPresets__types(state, types) {
// console.log('changeDeliveryPresets__types');
Vue.set(state.presets.delivery, "types", types);
// state.presets.delivery.types = types;
},
changeDeliveryPresets__methods(state, methods) {
Vue.set(state.presets.delivery, "methods", methods);
// state.presets.delivery.methods = methods;
},
changeDeliveryPresets__tc_methods(state, tc_methods) {
Vue.set(state.presets.delivery, "tc_methods", tc_methods);
// state.presets.delivery.tc_methods = tc_methods;
},
changeDeliveryPresets__tc_list(state, tc_list) {
Vue.set(state.presets.delivery, "tc_list", tc_list);
// state.presets.delivery.tc_list = tc_list;
},
changeDeliveryPresets__addresses(state, addresses) {
Vue.set(state.presets.delivery, "addresses", addresses);
// state.presets.delivery.addresses = addresses;
},
changeDelivery(state, delivery) {
for (let key in delivery) {
Vue.set(state.summary.delivery, key, delivery[key]);
// state.summary.delivery[key]=delivery[key];
}
},
changeDelivery__tc_city(state, tc_city) {
Vue.set(state.summary.delivery, "delivery_tc_city", tc_city);
// state.summary.delivery.delivery_tc_city = tc_city;
},
changeDelivery__tc(state, tc) {
Vue.set(state.summary.delivery, "delivery_tc", tc);
// state.summary.delivery.delivery_tc = tc;
},
changeDelivery__method(state, method) {
Vue.set(state.summary.delivery, "delivery_method", method);
// state.summary.delivery.delivery_method = method;
},
changeDelivery__delivery_type(state, delivery_type) {
console.log("setting delivery");
Vue.set(state.summary.delivery, "delivery_type", delivery_type);
// state.summary.delivery.delivery_type = delivery_type;
},
changeDelivery__address_id(state, address_id) {
Vue.set(state.summary.delivery, "delivery_address_id", address_id);
// state.summary.delivery.delivery_address_id = address_id;
},
changeDelivery__address(state) {
state.summary.address = {};
if (state && state.summary.delivery) {
if (state.presets && state.presets.addresses && state.summary.delivery && ((state.summary.delivery.delivery_method == "tc" && state.summary.delivery.delivery_tc_method == "door") || state.summary.delivery.delivery_method == "courier")) {
if (state.presets && state.presets.addresses && state.summary.delivery && state.summary.delivery && state.summary.delivery.delivery_address_id) {
Vue.set(
state.summary,
"address",
state.presets.addresses.find((address) => address.id == state.summary.delivery.delivery_address_id)
);
}
} else {
if (state.summary.delivery && state.summary.delivery.delivery_tc_city) {
Vue.set(state.summary, "address", {
address: state.summary.delivery.delivery_tc_city,
});
}
}
}
},
},
actions: {
//COMMON DATA
changeFillial: ({ commit }, { fillial }) => commit("changeFillial", fillial),
changePartnerId: ({ commit }, { partner_id }) => {
console.log("partner id commit");
commit("changePartnerId", partner_id);
},
changeContragentId: ({ commit }, { contragent_id }) => {
commit("changeContragentId", contragent_id);
},
changeContragents: ({ commit }, { contragents }) => {
commit("changeContragents", contragents);
},
changePartners: ({ commit }, { partners }) => {
commit("changePartners", partners);
},
//PRESETS
changeDeliveryPresets: ({ commit }, { presets }) => {
commit("changeDeliveryPresets", presets);
commit("changeDelivery__address");
},
changeDeliveryPresets__types: ({ commit }, { types }) => {
commit("changeDeliveryPresets__types", types);
},
changeDeliveryPresets__methods: ({ commit }, { methods }) => {
commit("changeDeliveryPresets__methods", methods);
},
changeDeliveryPresets__tc_methods: ({ commit }, { tc_methods }) => {
commit("changeDeliveryPresets__tc_methods", tc_methods);
},
changeDeliveryPresets__tc_list: ({ commit }, { tc_list }) => {
commit("changeDeliveryPresets__tc_list", tc_list);
},
changeDeliveryPresets__addresses: ({ commit }, { addresses }) => {
commit("changeDeliveryPresets__addresses", addresses);
},
//SUMMARY
changeDelivery: ({ commit }, { delivery }) => {
commit("changeDelivery", delivery);
commit("changeDelivery__address");
},
changeDelivery__tc_city: ({ commit }, { tc_city }) => {
commit("changeDelivery__tc_city", tc_city);
},
changeDelivery__tc: ({ commit }, { tc }) => {
commit("changeDelivery__tc", tc);
},
changeDelivery__tc_method: ({ commit }, { tc_method }) => {
commit("changeDelivery__tc_method", tc_method);
},
changeDelivery__delivery_type: ({ commit }, { delivery_type }) => {
commit("changeDelivery__delivery_type", delivery_type);
},
changeDelivery__delivery_method: ({ commit }, { delivery_method }) => {
commit("changeDelivery__delivery_method", delivery_method);
},
changeDelivery__address_id: ({ commit }, { address_id }) => {
commit("changeDelivery__address_id", address_id);
},
},
getters: {
summary: (state) => {
return state.summary;
},
presets: (state) => {
return state.presets;
},
delivery_tc_title: (state) => {
return state.presets && state.presets.delivery && state.presets.delivery.tc_list && state.summary && state.summary.delivery && state.summary.delivery.delivery_tc ? state.presets.delivery.tc_list[state.summary.delivery.delivery_tc] : "";
},
delivery_tc_method_title: (state) => {
return state.presets && state.presets.delivery && state.presets.delivery.tc_methods && state.summary && state.summary.delivery && state.summary.delivery.delivery_tc_method ? state.presets.delivery.tc_methods[state.summary.delivery.delivery_tc_method] : "";
},
contragent_id: (state) => {
return state.summary && state.summary.contragent_id ? state.summary.contragent_id : "";
},
contragent: (state) => {
return state.presets && state.presets.contragents && state.summary && state.summary.contragent_id ? state.presets.contragents[state.summary.contragent_id] : "";
},
partner_id: (state) => {
return state.summary && state.summary.partner_id ? state.summary.partner_id : "";
},
partner: (state) => {
return state.presets && state.presets.partners && state.presets.partners.length && state.summary && state.summary.partner_id ? state.presets.partners.find((partner) => partner.id == state.summary.partner_id) : "";
},
partners: (state) => {
return state.presets && state.presets.partners ? state.presets.partners : "";
},
contragents: (state) => {
return state.presets && state.presets.contragents ? state.presets.contragents : "";
},
delivery: (state) => {
return state.summary && state.summary.delivery ? state.summary.delivery : "";
},
delivery_presets: (state) => {
return state.presets && state.presets.delivery ? state.presets.delivery : "";
},
delivery_settings: (state, getters) => {
return {
delivery: getters["delivery"],
address: getters["address"],
fillial: getters["fillial"],
};
},
fillial: (state) => {
return state.summary && state.summary.fillial ? state.summary.fillial : "";
},
},
};
In the template the
{{ presets }}
{{ settings}}
returns { "types": {}, "methods": {}, "tc_methods": {}, "tc_list": {}, "addresses": [] } { "delivery": { "delivery_type": "", "delivery_method": "", "delivery_tc": "", "delivery_tc_method": "", "delivery_tc_city": "", "delivery_address_id": "" }, "fillial": { "address": "" } }
like initial in store
When i use getter in console appData.getters["basket/delivery_settings"]
it return the valid real time object
Also settimeouts like that
mounted() {
setTimeout(() => {
console.log(this.presets);
console.log(this.settings);
}, 10000);
},
returns the valid object too.
Whats is my mistake?Can someone help me?
The setters of computed are returning. Instead, they should be committing.
Think of getter + setter computed as a collection of read (getter) and write (setter) functions.
Let's take one of the computed apart:
contragent_id: {
get() {
return appData.getters["basket/contragent_id"];
},
set(value) {
return value;
},
}
Let's consider a read operation:
const myValue = this.contragent_id
if the code would be able to describe what it does, it would be saying something like:
I read the value from appData.getters["basket/contragent_id"] (which returns the value of appData.state.summary.contragent_id) and store it in a constant named myValue.
Great! That's exactly what it should be doing. Now let's consider a write operation (a setter):
console.log(this.contragent_id) // Expect: ''; Receive: ''
this.contragent_id = '42'
console.log(this.contragent_id) // Expect: '42'. Receive: ''
the current code (return value) would be described by:
Here's "42"! I'm giving it back to you, I'm not doing anything with it.
It should be described by:
I write '42' into state.summary.contragent_id, by committing this value to the 'basket/changeContragentId' mutation.
, which would look like:
set(value) {
appData.commit('basket/changeContragentId', value)
}
Once the mutation is performed, because of it, the getter immediately updates and starts returning the current value of state.summary.contragent_id, via getters['basket/contragent_id'], which is now 42 (or whatever we assigned).
In other words, with the committing setter, the above code will produce:
console.log(this.contragent_id) // Expect: ''; Receive: ''
this.contragent_id = '42'
console.log(this.contragent_id) // Expect: '42'; Receive: '42'
So the local computed contragent_id can now be read from and written to. In fact, we'd be interacting with state.summary.contragent_id, via getters and mutations.
On a separate note, we shouldn't be using Vue.set() everywhere in our mutations.
We probably want to write the above mutation as:
changeContragentId(state, contragent_id) {
state.summary = { ...state.summary, contragent_id };
}
Why?
{ ...state.summary, contragent_id }
is shorthand for:
{ ...state.summary, contragent_id: contragent_id }
, which creates a fresh object from state.summary containing everything that state.summary contained, plus the passed argument contragent_id's value, assigned to the contragent_id property of this new object, regardless of whether or not the old state.summary had such a property or any value in it. By assignment, state.summary's value is replaced with this new object. This replacement is what notifies the getters which, in turn, update all components using them (or reading directly from state).
This is the key: replacing the root prop of the state.
If we would have used
state.summary.contragent_id = value
state.summary object wouldn't have been replaced, and the change would not be visible in <template>.
In some cases (when something else is changed at the same time), we might see changes made to deep properties, giving a wrong impression about how Vue works.
I see a lot of repetition in both mutations and getters. It's unnecessary.
For example, we could replace all state.summary related mutations with a single one:
mutations: {
updateSummary(state, update) {
state.summary = { ...state.summary, ...update }
}
}
and now we could replace all state.summary related setters in components computed with calls to this mutation. Example:
computed: {
contragent_id: {
get() { return appData.getters['basket/contragent_id'] },
set(contragent_id) {
appData.commit('basket/updateSummary', { contragent_id })
}
},
partner_id: {
get() { return appData.getters['basket/partner_id'] },
set(partner_id) {
appData.commit('basket/updateSummary', { partner_id })
}
},
delivery: {
get() { return appData.getters['basket/delivery'] },
set(delivery) {
appData.commit('basket/updateSummary', { delivery })
}
},
fillial: (state) => {
get() { return appData.getters['basket/fillial'] },
set(fillial) {
appData.commit('basket/updateSummary', { fillial })
}
}
}
, which could be written as:
computed: {
...Object.assign(
{},
...["contragent_id", "partner_id", "delivery", "fillial"].map((key) => ({
[key]: {
get() {
return appData.getters[`basket/${key}`];
},
set(value) {
appData.commit("basket/updateSummary", { [key]: value });
},
},
}))
),
};
This looks complicated, doesn't it?
It's useful, we could re-use it in any component where we want to get or set state.summary props and all we'd have to do is specify a different array of keys, depending on what we want to expose.
So let's write a function, taking in the array of keys and place it in some storeHelpers.js file:
import { appData } from './path/to/appData'
export const mapSummary = (keys) =>
Object.assign(
{},
...keys.map((key) => ({
[key]: {
get() {
return appData.getters[`basket/${key}`];
},
set(value) {
appData.commit("basket/updateSummary", { [key]: value });
},
},
}))
);
Now we can
import { mapSummary } from './path/to/storeHelpers'
export default {
computed: {
...mapSummary(["contragent_id", "partner_id", "delivery", "fillial"])
}
}
Similarly, you could do this for any object you want to update inside the state, so you wouldn't have to write a mutation for each of its properties. In your case, you probably want to have updatePresets and updatePresetsDelivery mutation functions and mapPresets & mapPresetsDelivery helpers, because both state.presets and state.presets.delivery are objects.
If your state has a lot of objects inside other objects, rather than writing one mutation and one mapper function for each individual object (which is still an improvement over writing a mutation for each individual object property), you might consider a single updateBasket mutation and one mapBasket helper which would also take the object's path as a parameter. Now, that mutation, having a dynamic path, would be a good use case for Vue.set().
Keep in mind nesting objects inside other objects inside a state is generally a sign of poor architecture. In your specific case, I'd probably go for three separate stores: one called basketSummary, one called basketPresets and one called basketPresetsDelivery (or basketDelivery).
Alternatively, you could go for nested stores, which would be be basket/summary, basket/presets and basket/presets/delivery, since you're using namespacing. Namespacing was actually developed to address cases like yours.
This subject is debatable (a lot of developers have strong opinions about store architecture) but, from my experience, having many smaller stores, each controlling a flat structure (a level: the properties of only one object) is generally preferable to having one big store, with lots of getters, actions and mutations, each having multiple levels of object spreading (or having to use Vue.set()).
It simplifies testing and debugging.
Ultimately, it allows more granular/precise control over complex data structures, considerably reducing the time spent developing (and debugging).
Readability in getters could also be improved:
getters: {
contragent_id: (state) => {
return state.summary && state.summary.contragent_id
? state.summary.contragent_id
: "";
}
}
could be written as:
getters: {
contragent_id: (state) => state.summary?.contragent_id || ""
}

Uncaught Error: Module parse failed: Shorthand property assignments are valid only in destructuring patterns

I get this error:
Uncaught Error: Module parse failed: Shorthand property assignments are valid only in destructuring patterns (74:14)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| dispatch('ADD_CHILDREN_TO_NODE', {
> doc = doc,
| })
| .finally(() => {
at eval (document-flow.module.js:1)
at Object../src/main/code/customers-self-data/vuex/modules/document-flow.module.js (_bundle.js?97212a2ac8be2d4b571f:8449)
at __webpack_require__ (_bundle.js?97212a2ac8be2d4b571f:20)
at eval (store.js:8)
at Module../src/main/code/customers-self-data/vuex/store.js (_bundle.js?97212a2ac8be2d4b571f:8473)
at __webpack_require__ (_bundle.js?97212a2ac8be2d4b571f:20)
at eval (index.js:3)
at Module../src/main/code/customers-self-data/index.js (_bundle.js?97212a2ac8be2d4b571f:8378)
at __webpack_require__ (_bundle.js?97212a2ac8be2d4b571f:20)
at eval (index.js:1)
This is my module:
import * as a from "../types/actions.types";
import * as g from "../types/getters.types";
import * as m from "../types/mutations.types";
import {
some imports
} from "#pn-js/core";
const documentFlow = {
namespaced: true,
state: {
documentFlowTree: null,
documentId: null,
childrens: null,
},
getters: {
[g.GET_DOCUMENT_FLOW_TREE](state) {
return state.documentFlowTree;
},
[g.GET_DOCUMENT_ID](state) {
return state.documentId;
},
[g.GET_CHILDRENS](state) {
return state.childrens;
},
},
mutations: {
[m.SET_DOCUMENT_FLOW_TREE](state, payload) {
state.documentFlowTree = payload;
},
[m.SET_DOCUMENT_ID](state, payload) {
state.documentId = payload.id;
},
[m.SET_CHILDRENS](state, payload) {
state.childrens = payload.childrens;
},
},
actions: {
[a.LOAD_DOCUMENT_FLOW_TREE]({ dispatch,commit, state }) {
var _documentTypeNamesMap = {
ORDER: order,
DELIVERY: delivery,
INVOICE: invoice,
};
let params = new ParamsBuilder(url)
.param(ParamsBuilder.UrlReplacements.ID, state.documentId)
.build();
let res = [];
return Http.get({ params }).then((response) => {
//Compongo il nodo root
let firstNodeText =
_documentTypeNamesMap.ORDER + ":\t" + state.documentId;
let doc = [];
if (response.result) {
Object.keys(response.result).forEach((key) => {
doc.push(response.result[key].sequentDocuments.filter((d) => {
return d.docType.category === "DELIVERY";
}));
});
}
dispatch('ADD_CHILDREN_TO_NODE', { ====> This generates the error
doc = doc,
})
.finally(() => {
if (response.result) {
res.push({
text: firstNodeText,
state: { expanded: true },
children: state.childrens,
});
} else {
res = [
{
text: firstNodeText,
state: { expanded: true },
children: [{ text: noDataFound }],
},
];
}
commit(m.SET_DOCUMENT_FLOW_TREE, res);
});
});
},
[a.UPDATE_DOCUMENT_ID]({ commit }, payload) {
commit(m.SET_DOCUMENT_ID, payload);
},
[a.ADD_CHILDREN_TO_NODE]({commit},payload) {
let doc = payload.doc;
let childrens = [];
let matRegNodeText = "";
let i = 0;
Object.keys(doc).forEach((key) =>{
let docId = doc[key][0].docNum;
let deliveryParams = new ParamsBuilder(url)
.param(ParamsBuilder.UrlReplacements.NUM, docId)
.build();
Http.get({
params: deliveryParams,
}).then((deliveryResponse) => {
if (deliveryResponse.result) {
matRegNodeText =
(doc[key][0].docType.category === "DELIVERY" ? goodsIssue : null) +
"\t\t\t" +
deliveryResponse.result.goodsReceiptNum +
"\t\t\t" +
deliveryResponse.result.actualMovDate;
}
let child = {
text: Strings.fsa.cdp.df.position + "\t" + response.result[i].docPos.posNum,
state: { expanded: true },
children: [{ text: matRegNodeText }],
};
childrens.push(child);
i++;
});
});
commit(m.SET_CHILDRENS,childrens);
}
},
};
export default documentFlow;
My question: is it possible to call an action from an action on the same module?
My problem is that before I didn't use the action to build the node (in the action loop my object doc to retrieve the data) but before being able to push the array childrens into property children of the object res, it was called asynchronous the commit, I thought about putting that piece of code inside a promise and then building the tree node but the result was the same.

How to use realm with async fetch request?

I have meet this situation for my requirements:
step 1. save data to local db which in the mobile phone (realm)
step 2. upload the local data to the server, and the server will return the data ids if success
step 3. delete the records in local db by the returned ids which get by step2
Realm.open({schema:[MySchame],encryptionKey:getRealmKey()})
.then(realm =>{
realm.write(() => {
// 1. get all step data from db
let objetcs = realm.objects('MySchema');
// 2. upload obtained data to server
if(objetcs.length > 0){
let recordArr = [];
for (let o of steps){
recordArr.push(o.get());
}
uploadDataToServer(recordArr,(res)=>{
//3. filter the uploaded steps and delete them
let uploadedSteps = realm.objects('MySchema').filtered('id=$0',res.id);
if(uploadedSteps.length > 0){
realm.delete(uploadedSteps);
}
});
}
});
realm.close();
})
.catch(error =>{
console.log(error);
});
but this is not works as expected, it seems DB is closed too early than networks success callback.
Thanks for any ideas.
Finally ,I use realm like this:
let realm = new Realm({schema:[JOB_SCHEMA.jobTrack],encryptionKey:getRealmKey()});
let objects = realm.objects('JobTrack');
realm.beginTransaction();
realm.delete(objects);
realm.commitTransaction();
realm.close();
First create a service like one below
import repository from "./realmConfig";
let CatalogsService = {
findAll: function () {
return repository.objects("CatalogsModel");
},
save: function (catalogs) {
repository.write(() => {
repository.create("CatalogsModel", catalogs);
});
},
delete: function () {
repository.write(() => {
let all = repository.objects("CatalogsModel");
repository.delete(all);
});
},
update: function (catalogs, callback) {
if (!callback) return;
repository.write(() => {
callback();
catalogs.updatedAt = new Date();
});
}
};
module.exports = CatalogsService;
where my realmConfig file is as
import Realm from "realm";
class CatalogsModel extends Realm.Object { }
CatalogsModel.schema = {
name: "CatalogsModel",
primaryKey: "id",
properties: {
id: "string",
name: "string",
url: "string",
status: "int"
}
};
class OffersModel extends Realm.Object { }
OffersModel.schema = {
name: "OffersModel",
primaryKey: "id",
properties: {
id: "string",
name: "string",
url: "string",
status: "int",
machineId: "string",
machineName: "string"
}
};
export default new Realm({
schema: [CatalogsModel, OffersModel],
schemaVersion: 1,
deleteRealmIfMigrationNeeded: true
});
Now import Service.js where you are calling async server call and do your job. For reference see below code
import CatalogService from './path/to/CatalogService .js'
//get objects
var catalogs = CatalogsService.findAll();
// fire async function , I prefer axios for network calls
Axios.post("SERVER_URL", {
data: catalogs
})
.then(function (response) {
if (response.success)
CatalogsService.delete()
}
I assume you can easily modify findAll() and delete() method as per your need

GraphQL buildSchema vs GraphQLObjectType

I went through GraphQL's Object Types tutorial and then read through the Constructing Types part of the docs. I did a similar style trial by creating a simplecase convention converter. Why? To learn :)
When converting to using GraphQLObjectType, I wanted the same results as buildSchema.
Why does buildSchema use type CaseConventions but when using GraphQLObjectType it is not set at a type? Am I doing something wrong here?
Did I implement this with any alarming problems?
Should I be using a rootValue object with the GraphQLObjectType version as I did with the buildQuery version?
Thank you for your patience and help.
Both versions use this Object:
class CaseConventions {
constructor(text) {
this.text = text;
this.lowerCase = String.prototype.toLowerCase;
this.upperCase = String.prototype.toUpperCase;
}
splitTargetInput(caseOption) {
if(caseOption)
return caseOption.call(this.text).split(' ');
return this.text.split(' ');
}
cssCase() {
const wordList = this.splitTargetInput(this.lowerCase);
return wordList.join('-');
}
constCase() {
const wordList = this.splitTargetInput(this.upperCase);
return wordList.join('_');
}
}
module.exports = CaseConventions;
buildSchema version:
const schema = new buildSchema(`
type CaseConventions {
cssCase: String
constCase: String
}
type Query {
convertCase(textToConvert: String!): CaseConventions
}
`);
const root = {
convertCase: ({ textToConvert }) => {
return new CaseConventions(textToConvert);
}
};
app.use('/graphql', GraphQLHTTP({
graphiql: true,
rootValue: root,
schema
}));
GraphQLObjectType version:
const QueryType = new GraphQLObjectType({
name: 'Query',
fields: {
cssCase: {
type: GraphQLString,
args: { textToConvert: { type: GraphQLString } },
resolve(parentValue) {
return parentValue.cssCase();
}
},
constCase: {
type: GraphQLString,
args: { textToConvert: { type: GraphQLString } },
resolve(parentValue) {
return parentValue.constCase()
}
}
}
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
convertCase: {
type: QueryType,
args: { textToConvert: { type: GraphQLString } },
resolve(p, { textToConvert }) {
return new CaseConventions(textToConvert);
}
}
}
});
const schema = new GraphQLSchema({
query: RootQuery
});
app.use('/graphql', GraphQLHTTP({
graphiql: true,
schema
}));
I will try to answer you question satisfactorily.
Why does buildSchema use type CaseConventions but when using GraphQLObjectType it is not set at a type? Am I doing something wrong here
They are two different ways of implementation. Using buildSchema uses the graphQL schema language while GraphQLSchema does not use the schema language, it creates the schema programmatically.
Did I implement this with any alarming problems?
Nope
Should I be using a rootValue object with the GraphQLObjectType version as I did with the buildQuery version?
No, In buildSchema, the root provides the resolvers while in using
GraphQLSchema, the root level resolvers are implemented on the Query and Mutation types rather than on a root object.

Realm "observer.next create #[native code]" exception

I am trying to fetch data with apollo and then write it to realm. I have created a js file that I know works, because it has worked before. But, when I try to write to a particular model I get an error message. More details as follows:
Code (Not entire code) LocationQuery.js:
const realm = new Realm({ schema: [testBuilding1], schemaVersion: 1 });
let buildingTypeArray = [];
const temp = [];
class LocationQuery extends Component {
static get propTypes() {
return {
data: React.PropTypes.shape({
loading: React.PropTypes.bool,
error: React.PropTypes.object,
sites: React.PropTypes.array,
}).isRequired,
};
}
render() {
if (this.props.data.loading) {
return (null);
}
if (this.props.data.error) {
return (<Text>An unexpected error occurred</Text>);
}
if (this.props.data.sites) {
this.props.data.sites.map((value) => {
buildingTypeArray.push(value.locations);
});
buildingTypeArray.forEach((locationValues) => {
realm.write(() => {
realm.create('testBuilding1', {
building: '273',
});
});
});
}
return null;
}
}
const locationQueryCall = gql`
query locationQueryCall($id: String!){
sites(id: $id){
locations {
building
type
}
}
}`;
const ViewWithData = graphql(locationQueryCall, {
options: props => ({
variables: {
id: 'SCH1',
},
}),
})(LocationQuery);
export default connect(mapStateToProp)(ViewWithData);
The error I get is a big red screen that read:
console.error: "Error in observe.next.... blah blah blah"
The Model I am using:
export const testBuilding1 = {
name: 'testBuilding1',
properties: {
building: 'string',
},
};
The weird thing is that the code works when I use this model:
export const locationScene = {
name: 'locationScene',
properties: {
building: 'string',
},
};
I am calling LocationQuery.js in another piece of code passing it through at render.
Thank you in advance for the help!