Meteor Server-side variable persist between methods - angularjs

I am building a simple Meteor-Angular 1 application and I am having a trouble to make my variable 'var conn' persist between methods in server.
Meteor code:
import {Meteor} from 'meteor/meteor';
var name;
Meteor.methods({
'setName': function () {
name = 'Harry';
},
'getName': function () {
console.log(name);
});
}
});
If I am calling setName and getName from the same template in Angular then name persists. If I set name in one template but call getName in another template, then name is 'undefined'. I came with Java background and don't know how to make meteor class persist as the same object between Angular templates. Thank you very much for help in advance.

You have 3 options:
Store it in a collection in MongoDB.
Use a global variable defined in a /server/xxx.js file.
Other server side persistence tools. Maybe https://github.com/lmaccherone/node-localstorage?
For alt 2, you could create a dictionary object and scope the data to the client connection by using the connection.id from Meteor.onConnection() [Docs].

i'm surprised it works at all. if that code is indeed running on the server, it's invoked in a new context on each call. if you want your data persisted, you need to persist in the database.

Related

How to extend web3js with TypeScript?

So I'm trying to build a prototype on React w/ TypeScript for an application that I'm developing - which in the future I'm going to migrate to Django, that's why I want to use web3js, to pass it later to web3.py - and a I wanna use the relay methods of Infura, so the users don't need to have a cryptowallet.
How I'm trying to do it is by following the Infura tutorial on ITX and getting everything on web3js. Right now what I have is this:
//Configure the provider
let web3 = new Web3(
new Web3.providers.HttpProvider(
`https://:${process.env.REACT_APP_PROJECT_SECRET}#${process.env.REACT_APP_ETHEREUM_NETWORK}.infura.io/v3/${process.env.REACT_APP_PROJECT_ID}`
)
);
web3.extend({
property: "relay",
methods: [
{
name: "getBalance",
call: "relay_getBalance",
params: 1
},
],
})
This is what I do at the start of the React component. Later, I wanna have a callback that, when I want, it'll retrieve the balance of the gas pool so it'll be something like:
() => web3.relay.getBalance(...)
The problem is that, when I try to use it like that, as the property doesn't exist on the Web3 class, I can't compile it. Is there a way to extend the class definition so I can define - and use - the relay methods inside its own module? I've tried with JS and works fine, but I would really like to keep the project on TS.

ReactJS external library

Hi I am quite new to reactjs but I started to understand few things. But this one giving me a headache, I have a small reactjs component that will be added in an existing site. The problem is inside my component I wanted to use a function in a JS file that is declared masterpage of the site. The name of the function I want to access is "SPClientPeoplePicker_InitStandaloneControlWrapper", so whenever I build my component I get the following error :
'SPClientPeoplePicker_InitStandaloneControlWrapper' is not defined no-undef
I tried using windom.SPClientPeoplePicker_InitStandaloneControlWrapper but the problem is in window "SPClientPeoplePicker_InitStandaloneControlWrapper" is giving me a different function. It would be nice if that library can be scoped inside my component
I tried calling library using import but it didnt work
import clientforms from "https://standardsSite.com/_layouts/15/clienttemplates.js";
I solve the problem I use loadjs its very handy.
loadjs(
[
"https://mysharepointsite.com/_layouts/15/clienttemplates.js",
"https://mysharepointsite.com/_layouts/15/clientforms.js",
"https://mysharepointsite.com/_layouts/15/clientpeoplepicker.js",
"https://mysharepointsite.com/_layouts/15/autofill.js"
],
"SPLibrary"
);
let self = this;
loadjs.ready("SPLibrary", function() {
self.handleSubmit(self.props.name);
});

How to make the UI respond to subscriptions in Apollo

I'm using react-apollo as a client to communicate with a GraphQL server that I created. I managed to successfully get subscriptions working with the data.subscribeToMore() function as detailed in the Apollo documentation and the up-to-date data shows up when I run my web application inside of two windows. What I'm trying to do is make it so that an notification alert gets displayed when another client changes data that I'm currently looking at so that I can tell that something changed in case I wasn't paying attention? What would be the correct way of doing this?
update method?
updateQueries method?
The dataFromObjectId and refetchQueries fields did not seem relevant for what I was trying to do. Since I'm using redux, is there a way I could dispatch actions directly from my subscription? Would notification alerts be something that I have to use client.subscribe() with?
Assuming you're using the latest version of Apollo, you should be handing the component a prop named "updateQuery" that contains logic for handling the data.
http://dev.apollodata.com/react/subscriptions.html#subscribe-to-more
This section goes over what you need to do, but essentially your "updateQuery" function should do the following:
Take in an object of structure argumentName.data which contains the new information.
Adds the new object to the results by creating a new object.
Returns the new results object.
so it might look something like this:
(prev, { subscriptionData }) => {
if (!subscription.data) {
//If no new data, return old results
return prev;
}
var newResults = Object.assign(
{},
prev,
queryName: { [subscriptionData.data, ...prev[queryName]] }
);
return newResults;

How to replace a React component

I plan to have a base app where most of the components should be replaceable at a later time, depending on specific customer needs without touching the base app code. What is the best mechanism to achieve this within the React ecosystem? Is there a registry that can be updated, or any other deferred binding of components similar to the GWT replace-with construct? Thanks.
Update 1:
My understanding is that Dependency Injection would allow one to inject into static components. The question I'm asking is more about whether it's possible to implement a registry of sorts and compose the application via component registry keys, thus enabling later updates to specify which component that key will be resolved to. React seems to expect a static relation there, and I want it to be dynamic if possible.
No, there's no central registry, but it wouldn't be too difficult to create one. Something like (sorry about mixing JS syntaxes)
// Registry module
var Component1 = require('component1')
var components = { Component1 }
var replace = function(name, cfn) { components[name] = cfn }
// Render module
var registry = require('registry')
var Component1 = registry.components['Component1']
render...Component1
// Override module
var registry = require('registry')
var Component1override = require('component1override')
registry.replace('Component1', Component1override)
The only trick is to make certain that the Override module gets loaded before the Render module.

Data models and business logic in isomorphic (React/Redux/Express/Mongo) app

I've recently built a few isomporphic/univeral projects using the React-Redux-Express-Mongoose stack.
In my mongoose models is contained a lot of business-logic. As a very basic example (excuse my ES6):
import mongoose, {Schema} from 'mongoose';
const UserSchema = new Schema({
name: String,
password: String,
role: String
});
UserSchema.methods.canDoSomeBusinessLogic = function(){
return this.name === 'Jeff';
};
UserSchema.methods.isAdmin = function(){
return this.role === 'admin';
};
This is all great on the server, however when these models are hydrated in the browser as plain JSON objects, I then have to re-implement this same business logic in some React component or Redux reducer, which doesn't feel very clean to me. I'm wondering how best to approach this.
From reading around Mongoose, there seems to be limited browser support, mostly just for document validation. I suppose my main options are:
Move all the business logic into some "normal" JS classes, and instantiate those all over the place. For example:
# JS Class definition - classes/user.js
export default class User {
constructor(data = {}){
Object.assign(this,data);
}
canDoSomeBusinessLogic(){
return this.name === 'Jeff';
};
isAdmin(){
return this.role === 'admin';
}
}
# Server - api/controllers/user.js
import UserClass from
User.findById(1,function(err,user){
let user = new UserClass(user.toJSON();
});
# Client - reducers/User.js
export default function authReducer(state = null, action) {
switch (action.type) {
case GET_USER:
return new UserClass(action.response.data);
}
}
# Client - containers/Page.jsx
import {connect} from 'react-redux';
#connect(state => ({user: state.user}))
export default class Page extends React.Component {
render(){
if(this.props.user.isAdmin()){
// Some admin
}
}
}
Move all the business logic into a some static helper functions. I won't write out the whole example again, but essentially:
# helpers/user.js
export function isAdmin(user){
return user.role === 'admin';
}
I suppose the difference between the above 2 is just personal preference. But does anyone have any other thoughts about isomorphic apps and data modelling? Or have seen any open-source example of people solving this problem.
As an extension to the above, what about an isomorphic save() function e.g. User.save(). So if called on the client it could do a POST to the relevant API endpoint, and if run on the server it would call the Mongoose save() function.
Spoiler: Expect an opinionated reply. There is no 'right' way to do it.
First of all, I want to make the difference between isomorphic and universal clear, so that you know exactly what we are talking about:
Isomorphism is the functional aspect of seamlessly switching between client- and server-side rendering without losing state. Universal is a term used to emphasize the fact that a particular piece of JavaScript code is able to run in multiple environments.
Is it worth it that much abstraction into an universal app?
Generally what you want an universal app for is to have the client and the server that pre-renders the app both loading the same code. Although you can run the API from the same server that pre-renders the app, I would rather proxy it and run it in a different process.
Let me show you two different React repositories:
React + API erikras/react-redux-universal-hot-example
React wellyshen/react-cool-starter
Erikras well-known boilerplate uses his universal app to share dependencies globally, and code between the server that pre-renders the page and the client. Although he could, he does not share validation. Survey API validation Survey client validation
Wellyshen does not have an API, but he also shares his dependencies and code, though only between the server and the client. The server loads the routes, the store and everything that is being run by the client app. That is to provide isomorphism.
Having said that, it is up to you whether to move all validation in one place. I probably would just consider it for complicated validation cases, like an email validation which you could actually have a helper for that. (that was just an example, for email validation you already have validator). In certain occasions, it might be more convenient to rely on the API validation, albeit not being the best practice.
Simple validations, like the ones in your examples, can be done effortless with redux-form anyway, which that I know there is no direct way to translate it on the API. Instead you should probably be looking for express-validator on it.
One more thing, despite the fact that a few very popular React boilerplates will have the API and client together, I tend to work with two different repositories: the React + server-side rendering and the API. In the long term run it will result in a cleaner code that will be totally independent one from the other. organizing-large-react-applications

Resources