问题
I am in the process of creating a mobile and web version of an app using ReactJS and iOS respectively. Both of these platforms will pull data down from a Firestore database to use but I am wondering what is the best way to only write business logic once in order to do operations on the database?
For instance, on both apps you will click a button that updates a field in the Firestore database, instead of writing the logic to do this in Javascript and then Swift, is there a best practice to only have to write the logic once and then call the same logic from both platforms?
Would cloud functions be the best way to achieve this? Could I write one cloud function in say Go, and then call this cloud function from both the iOS app in switft and ReactJS app in javascript? Is this best practice?
回答1:
Using Cloud Functions to increase the amount of shared code is indeed a common use-case. A fairly regular pattern is to use Cloud Functions for more complex writes, where the client merely calls a single function, which then contains the more complex code. I'd still keep simpler write operations in the application code itself, but that is a matter of preference.
Note that if the duplicated code is a fan-out operation, you can also have the client write the primary document to the database itself, and then have that trigger a Cloud Function to perform the fan-out. That way the client still gets the benefits of writing through the SDK (e.g. it works offline), but some of the code is on the server and thus reused between clients.
I also see many developers creating Cloud Functions to join all the data they need. So that way the client can do just one call to get data from multiple collections. I'm not a big fan of that myself however, because you lose the offline and realtime capabilities of the Cloud Firestore SDKs that way.
来源:https://stackoverflow.com/questions/54484869/best-way-to-use-business-logic-across-multiple-platforms-cloud-functions