how to update a function on server side but keep the one on client side unchanged - client-server

Server side:
function sender(x, y){
do something
}
Client side:
function receiver(x,y){
do something
}
Now, somehow we need to change the function on server side to only need one parameter:
function sender(x){
do something
}
Without changing/updating the function on client side, how can we keep these two functions working with each other?

You might want to make a wrapper for the new function. like this:
function sender(x,y) {sender(x)}

Related

How can I call a back-end service function from the Success function of the MainCell in the front-end in a JAMstack RedwoodJS app?

I'm using RedwoodJS.
My front-end (what they call the "web" "side") has (among other files) a HomePage.ts and MainCell.ts, and then the Success function in MainCell calls a 3rd party API.
Everything is working.
However, I now want to start caching the results from the 3rd party API.
I've created a database table and a back-end "service" called cachedQueries.ts (using Prisma), which has:
export async function getFromCacheOrFresh(key: string, getFresh: Function, expiresInSec: number): Promise<any> {
const nowMoment = dayjs.utc();
const nowStr = nowMoment.format(dbTimeFormatUtc);
const cached = await getCachedQuery({ key, expiresAtCutoff: nowStr });
console.log('getFromCacheOrFresh cached', cached);
if (cached) {
const cachedValueParsed = JSON.parse(cached.value);
console.log('cachedValueParsed', cachedValueParsed);
return cachedValueParsed;
} else {
const fresh = await getFresh();
saveToCache(key, JSON.stringify(fresh), expiresInSec);
return fresh;
}
}
I have proven that this cachedQueries.ts service works and properly saves to and retrieves from the DB. I.e. for any 3rd-party APIs that can be called from the back-end (instead of from the front-end), the flow all works well.
Now my challenge is to enable it to cache front-end 3rd-party API queries too.
How I can call my getFromCacheOrFresh function from the Success function of the MainCell in the front-end?
I must be confused about Apollo, GraphQL, RedwoodJS, Prisma, etc relate to each other.
P.S. Client-side caching will not suffice. I really need the 3rd-party API results to be saved in the DB on my server.
I eventually figured it out.
I created a new cell called GeoCell, and I'm returning an empty string for each function of GeoCell (Success, Loading, Empty, and Failure).
That feels weird but works.
What was unintuitive to me was the idea that I was required to use a JSX component (since Apollo would never let me query or mutate GraphQL outside of a JSX component), but I didn’t want the cell component to actually display anything… because all that it needs to do in its Success is call a helper function that affects elements aleady created by a different cell (i.e. addMarkerAndInfoWindow affects the div of the existing Google Map but doesn’t display anything where the GeoCell was actually located).
As https://stackoverflow.com/a/65373314/470749 mentions, there's a related discussion on the Redwood Community Forum: Thinking about patterns for services, GraphQL, Apollo, cells, etc.

Using data stored in cache/storage instead of database

I was thinking about using cache/storage to store source for api routes which doesnt update that much. I mean i would like to update stored data every one minute (example) and my routes will use that data as source instead of database as source. It will make less database queries. Im I thinking in good way? How to achieve that in Laravel?
You could setup an instance of memcached which is supported by Laravel. The Laravel caching documentation is a good place to start learning how to setup a cache driver for memcached. Once setup, your logic could look something like this:
if (Cache::has('key')) {
//your key exists in the cache. get it.
$value = Cache::get('key');
//and use it
useMyValue($value);
}
else
{
//the cache does not contain the key you are looking for
//you can get it from the DB and cache it.
//the next time your function runs it will get the value from cache instead
//of reading from the db
$value = Cache::get('key', function () {
return DB::table(...)->get();
});
//and use your value now like normal
useMyValue()
}

Parse.com - Cloud function call from another cloud function makes request.user null

I've written a Cloud function ("newUserLog") that i call from the iOS SDK and everything works correctly. the cloud function heavily uses "request.user".
Now i've made another cloud function ("doStats"), and in that function at some scenarios, i need to call "newUserLog" function.
I do this with
Parse.Cloud.run("newUserLog").then(function(logCreated){
...
});
But at "newUserLog" function, request.user is null.
What is the best practice to solve this kind of problem? i know i can pass the request.user pointer and fetch it again, but i'm afraid it's less secure and i'll have to do alot of refactoring.
Is there a simple way transferring request.user from one cloud function to another?
Thanks alot
Or
Don't call one cloud function from another if you can help it. Instead, create plain JS functions which hold your reusable logic and pass them a set of parameters. This is much easier to manage and much clearer about what those functions actually need in order to operate.
change newUserLog code to be something like:
var user;
if( request.User )
{
user = request.User;
}
else
{
user = new Parse.User();
user.id = request.params.userId;
}
In both cases you have basically the shell of the user, and will need to perform a fetch if you want the rest of the data.
Change your doStats method to pass in the userId as a parameter to the other cloud code function:
Parse.Cloud.run("newUserLog", {userId:request.User.id});
or
var user = request.User;
Parse.Cloud.run("newUserLog", {userId:user.id});
That being said, you could consider creating a function that gets called by both doStats and newUserLog that is not a cloud code function, and pass relevant parameters into it from either of your cloud code functions.

Ember Ajax Calls running in serial

Setup:
blah is my ember app
find essentially calls Ember.$.ajax(url, params, method)
the find method isn't a blocking call
Neither of the routes nor controllers have dependencies (needs) on each other
Problem:
I'm trying to figure out why the setupController (I tried activate as well) in ApplicationRoute isn't being execute until after my ajax call returns from my CowRoutes model.
Thing's I've Tried:
If I move the code from the setupController into the model of CowRoute they all run in parallel (they don't belong here at all, especially since they are header footer and I might hit a different route beside CowRoute).
I tried using Ember.RSVP.resolve on my find method, everything still works, it's just still running in serial
ApplicationRoute
blah.ApplicationRoute = Ember.Route.extend({
// setupController runs If a route handler's context changes
setupController: function () {
this.controllerFor('meta_property').set('model', blah.MetaProperty.find('meta_property'));
this.controllerFor('header').set('model', blah.User.find("user"));
}
CowRoute
blah.CowRoute = blah.Route.extend({
model: function (params) {
//this.controllerFor('meta_property').set('model', blah.MetaProperty.find('meta_property'));
//this.controllerFor('header').set('model', blah.User.find("user"));
return blah.Cow.find('cow', params);
//return Ember.RSVP.resolve(blah.Cow.find('cow', params));
}
I guess Ember tries to execute all model hooks of all Routes available af first. It waits for the model hooks to finish before executing all setupController hooks.
Why could this make sense?
Let's have a look at the interface of setupController:
setupController: function(controller, model) {
...
}
Ember is passing the model it retrieved via the model hook into the setupController hook. This is why it has to wait.
But why does it wait for your CowRoutes model hook before running setupController on your ApplicationRoute?
I guess this is because, you might call controllerFor(name) inside setupController and Ember wants all models "to be in place".
But i think this behaviour should not hurt too much, since the model hook is just executed when the App is entered via URL for deserialization of parameters.
Note: This answer is just a guess from my side, but it seems to make sense to me. At least it should be in the right direction :-)
According to convention, If you have a model that is not in the url and across multiple routes, its ideal to put those in the application route ;)

Ajax / Json How to run an INSERT/UPDATE into mysql

Again related with my weekend project, I'm trying to learn a bit more of web-development. So I'm putting in the list of features i want to implement, some stuff i absolutely have no idea how to do.
I've been reading tutorials on how to use ajax, but i can't find a simple one, that i can copy-paste (with one or two changes) to see it work before i go into the how it works.
What I've been searching is just a simple example on an ajax function, that triggers a mysql insert or update. Anyone as a simple example on how to do this? I think it would prove a nice start to learn it. (Ajax or Json are both ok).
Correct me if I'm mystaken: I'm basing myself on this tutorial. So as obviously the client side doesn't have access to database calls, what I should do, would be something like creating a code snippet to add stuff to the database right? For example create an "addcomment.php" that can be called with xhr.open(GET, "addcomment.php?comment=mycomment", true);
Sounds like you got it right. Use Ajax to call a server side script which then does the database work for you.
A good setup is to use a framework like jQuery on the client side. This framework will encode and decode JSON automatically. On the server side you could create a class that handles all the ajax (or rather, ajaj, since we are using JSON) requests. Here is a short PHP file that shows the general idea. Add more elements to the functionMap array, and add the respective functions to the class.
class Ajaj{
private $callback = "";
private $functionMap = array( "select" => 'getIt');
function Ajaj(){
if(array_key_exists('jsoncallback',$_GET)){
$this->callback=$_GET['jsoncallback'];
}
}
function parse(){
echo "$this->callback(";
if(array_key_exists('action', $_POST)){
$action = $_POST['action'];
if(array_key_exists($action, $this->functionMap)){
echo $this->functionMap[$action];
}
}else{
echo "{}";
}
echo ")";
}
function getIt(){
return json_encode(//get the database stuff here);
}
}
$ajaj = new Ajaj();
$ajaj->parse();

Resources