Is it possible to add service redirect in development mode in Angular 6 - json

I'm working on an App in Angular 6. When the app is deployed, it exchanges data with an online database. When I'm working on the app, however, I would like it to exchange data with a local database. I have a single service setup to do all of the communication, so when I am working on the app I can simply change the base URL, but I was wondering if there was a way I could just redirect that service in development, and then have it go to the database as normal in the production environment.
I am aware I can add a proxy.conf.json file, which I'm already doing to access a separate online API, so I dont know if it is as simple as just adding another element to that json file.
I haven't posted any sample code as this is more of a general question as to methodology in angular versus a specific line of code question, but I'm happy to post whatever people would like to see for clarification.

You can do one thing,
you can configure your url in both environment.ts and environment.prod.ts like
environment = {
...
url: 'something.com/api',
...
}
and use it like
import { environment } from 'environment/environment';
const url = environment.url;
this will give you different url for normal build (Development env.) and prod build (Deploy env.)
Also, don't worry about using just environmet.ts in import statement, as when you create prod build your environment.ts gets content from environment.prod.ts. so you will be using url from environment.prod.ts

In Angular you have access to a function isDevMode() which determines if the app is currently in devmode.
Based on that, you should be able to adjust your base url as needed.
import { isDevMode } from '#angular/core';
private baseUrl: string = '';
const devUrl: string = '...';
const prodUrl: string = '...';
if (isDevMode()) {
this.baseUrl = devUrl
}
else {
this.baseUrl = prodUrl
};

Related

Using Google Secret Manager with Firebase Functions and Stripe (top level)

Gday,
Quite new to TS and only got a little bit of experience with backend in general, so apologies if I am completely missing the idea.
So I really like the idea of using Google Secret Manager instead of custom env config for Firebase Functions.
Below is all done within a config.ts within my functions dir.
I need to initialize stripe. Traditional tutorials say to do something like the below example:
import Stripe from 'stripe';
export const stripeSecret = functions.config().stripe.secret;
const stripe = new Stripe(stripeSecret, {apiVersion: '2020-08-27'});
I think it would be ideal to change it to this:
import Stripe from 'stripe'
import {SecretManagerServiceClient} from '#google-cloud/secret-manager';
export async function getSecret(name:string){
const [version] = await secrets.accessSecretVersion({
name: `projects/example/secrets/${name}/versions/latest`,
});
return version.payload?.data?.toString();
}
export const stripeSecret = await getSecret("Stripe-API")
const stripe = new Stripe(stripeSecret, {apiVersion: '2020-08-27'});
But this causes an issue with it being async/await on the top level.
What are my options here and what is best practice?
The Google Secret manager is a useful utility and below are a few best practices when using Secret Manager.
You may try and use following to create and use a secret:
From the root of your local project directory, run the following command:
firebase functions:secrets:set SECRET_NAME
Enter a value for SECRET_NAME.
The CLI echoes a success message and warns that you must deploy functions
for the change to take effect.
Before deploying, make sure your functions code allows the function to access the secret using the runWith parameter:
exports.processPayment = functions
// Make the secret available to this function
.runWith({ secrets: ["SECRET_NAME"] })
.onCall((data, context) => {
const myBillingService = initializeBillingService(
// reference the secret value
process.env.SECRET_NAME);
// Process the payment});
Deploy Cloud Functions:
firebase deploy --only functions
You can also access it like any other environment variable. Conversely, if another function that does not specify the secret in runWith tries to access the secret, it receives an undefined value:
To see the complete best practices list, please visit the next link [1] and to know more about managing secret versions, please take a look at the next link [2].
[1] https://cloud.google.com/secret-manager/docs/best-practices
[2] https://cloud.google.com/secret-manager/docs/managing-secret-versions

How to resolve dynamic routes on client side in Next js framework

I am currently on Next js using full static generation, as I want to serve all my pages from the S3 + cloudfront (no server involved). Next js has good support for this except when it comes to dynamic pages (ex: /posts/:id). All the framework features to solve this type of scenario involve either rendering all passible pages at build time (which is not viable) or having a server to render these pages that have dynamic routes (making, therefore, the site an hybrid app).
To continue to be full static I need to have a way around this.
In create react app one could use the react-router and resolve the routes on the client side, which is exactly what I want to do for the dynamic routes. But I as far as I know next js and the react-router are not compatible, so apparently that is not an option.
Based on what I know, I think Dynamic Route on SSG is supported. Dynamic route feature is independent of getServerSideProps or getStaticProps. you can just use next/router to get the param you need and render your page accordingly.
Here is the official example.
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { pid } = router.query
return <p>Post: {pid}</p>
}
export default Post
Reference
https://nextjs.org/docs/routing/dynamic-routes

Connecting Database with Svelte

I'm new to using Svelte and would like to create a ordering website using Svelte. I know that I will need a database to keep track of the order, customer name, price etc. I have used MySQL before but I haven't learned how to connect a database to a website.
Is there a specific database that you can use if you are using Svelte?
Or is there a way to connect MySQL to Svelte?
I have searched about this on Youtube and Google but I'm not sure if it's different if you are using Svelte so I wanted to make sure.
Note: I have not started this project yet so I do not have any code to show I just want to know how you can connect a database if you're using Svelte.
Svelte is a front end javascript framework that run on the browser.
Traditionally, in order to use databases like mysql from a front end project such as svelte, (that contains only html,css and js), you would have to do it with a separate backend project. You can then communicate the svelte app and the backend project with the help of REST api. The same applies to other other front end libraries/frameworks like react, angular vue etc.
There are still so many ways to achieve the result. Since you are focusing on Svelte here are few things options
1 Sapper
Sapper is an application framework powered by svelte. You can also write backend code using express or polka so that you can connect to database of your choice (mysql / mongodb)
2 User Server less database
If you want you app simple and just focus on svelte app, you can use cloud based databases such as firebase. Svelte can directly talk to them via their javascript SDK.
3 monolithic architecture
To connect with mysql in the backend, you would need to use one serverside application programming language such as nodejs (express) php or python or whatever you are familiar with. Then use can embed svelte app or use api to pass data to the svelte app.
I can make an example with mongodb
You have to install the library
npm install mongodb
or add in package.json
Then you have to make a connection file that you have to call everytime you need to use the db
const mongo = require("mongodb");
let client = null;
let db = null;
export async function init() {
if(!client) {
client = await mongo.MongoClient.connect("mongodb://localhost");
db = client.db("name-of-your-db");
}
return { client, db }
}
for a complete example with insert you can see this video
https://www.youtube.com/watch?v=Mey2KZDog_A
You can use pouchdb, which gives you direct access to the indexedDB in the browser. No backend needed for this.
The client-pouchdb can then be replicated/synced with a remote couchdb. This can all be done inside you svelte-app from the client-side.
It is pretty easy to setup.
var db = new PouchDB('dbname');
db.put({
_id: 'dave#gmail.com',
name: 'David',
age: 69
});
db.changes().on('change', function() {
console.log('Ch-Ch-Changes');
});
db.replicate.to('http://example.com/mydb');
more on pouchdb.com
Also the client can save the data offline first and later connect to a remote database.
As i get question mostly about connection to backend, not a database. It is pity, but svelte app template has no way to connect backend "in box".
What about me, i'm using express middleware in front of rollup server. In this case you able to proxy some requests to backend server. Check code below
const proxy = require('express-http-proxy');
const app = require('express')();
app.use('/data/', proxy(
'http://backend/data',
{
proxyReqPathResolver: req => {
return '/data'+ req.url;
}
}
)
);
app.use('/', proxy('http://127.0.0.1:5000'));
app.listen(5001);
This script opend 5001 port where you have /data/ url proxied to backend server. And 5000 port still available from rollup server. So at http://localhost:5001/ you have svelte intance, connected to backend vi /data/ url, here you can send requests for fetching some data from database.

Using Firebase Database (with Imported JSON file) in Ionic 3

I'm new to Firebase and I previously had a JSON file consisting of data I was using in my app, this JSON file was hosted on my own sever - and was working well with my app. Now I'd like to expand the app and try using Firebase to enhance it.
I've gone ahead and created a new account and all and imported my JSON file into firebase, now I'd like to know how I can possibly retrieve this data - I know that simply changing the path to my JSON file might not just be it! Can anyone assist?
Thanks & Regards...
I'm assuming you've already configured the Firebase in your project and installed it, if not just tell me and i'll update my answer.
If you've imported your JSON data into Firebase and you can see it under database on your console now all you'll need to do to read this data is a simple .once() or .on() (i'll explain the differences).
In the page you want to fetch data do this:
import * as firebase from 'firebase';
// LET'S SAY YOU WANT TO FETCH SOMETHING ON HOME PAGE
export class HomePage {
// THIS IS THE PROPERTY WE'LL USE TO SAVE YOUR DATA
private myFirebaseData: any;
constructor(){}
// LET'S FETCH DATA WHEN THE USER FIRST LOADS THE PAGE
ionViewWillLoad(){
firebase.database().ref('Users').once('value', snapshot => {
this.myFirebaseData = snapshot.val();
});
};
}
So explaining a little more of what i've done:
.ref(<string>) is the reference of a node in your firebase database, here i'm fetching all users. You can go as deep as you want, let's say you want the name of a user and you know his ID, you can use .ref(Users/${this.userID}/name) and this'll return his name.
.once() is used to read the data once and value is saying i'll get all the value in the referenced node. You can use .on() and this'll create an observable in that node for the value event. There are other events you can use with .on() and they are child_added, child_moved, child_changed and child_removed.
snapshot.val() is getting all data returned from my callback function.
Here's some useful docs:
Read Events
Querying data
Read, write, delete, update
Hope this helps.
EDIT
Let's say you haven't configured your application to use Firebase, here's the needed steps. Just an observation: i don't use AngularFire2, the methods can be a little differents.
1 - You'll need to install Firebase, so in your project folder use npm install --save firebase on your command console.
2 - In your app.component.js you'll configure your Firebase to point to your project:
import * as firebase from 'firebase';
export class MyApp {
constructor(){
firebase.initializeApp({
apiKey: "key",
authDomain: "domain",
databaseURL: "https://...",
projectId: id",
storageBucket: "bucket",
messagingSenderId: "id"
});
}
}
3 - The properties i used to configure Firebase can be obtained when in your project Firebase console under Settings > general > Add app > Add firebase to your web app (Or something like that).
This is all you'll need and you're ready to use Firebase.

Is it possible to export React single page website as HTML?

I have a single page web application using React and materialize-css and I would like to export it as static HTML and CSS so that it is possible to easily edit HTML for the purpose of prototyping. Is it possible to export at least a snapshot of current state?
I tried "save page" in Firefox and Chrome, but it does not provide good results.
Follow the following steps :-
1. In brouser, got to the developer tools,
2. select Inspector(firefox)/Elements(chrome),
3. then select the tag HTML, right click on it,
4. then click Edit as HTML.
Now you can copy all the code and save it. While the color and shape of the document remains, you will miss the pictures.
Good luck ! :)
Probably not ideal, but you can store the entire page as a variable and download it. Run this in your browser console after the page has loaded:
var pageHTML = document.documentElement.outerHTML;
var tempEl = document.createElement('a');
tempEl.href = 'data:attachment/text,' + encodeURI(pageHTML);
tempEl.target = '_blank';
tempEl.download = 'thispage.html';
tempEl.click();
The ReactDOMServer module contains a function for rendering a React application to static HTML - it's designed for use on the server, but I don't think there's anything to stop you using it in the browser (don't do this in production though!)
import ReactDOMServer from "react-dom/server";
import App from "./yourComponent";
document.body.innerHTML = ReactDOMServer.renderToStaticMarkup(App);
var pageHTML = window.document.getElementById('divToPDF').innerHTML;
let data = new Blob([pageHTML], {type: 'data:attachment/text,'});
let csvURL = window.URL.createObjectURL(data);
let tempLink = document.createElement('a');
tempLink.href = csvURL;
tempLink.setAttribute('download', 'Graph.html');
tempLink.click();
You can build your code and host it on github.io. The following tutorial will help you achieve that. You can then use the generated code in the gh-pages branch as your exported HTML
This was the first thread I found on SW.. so I think it would be appropriate to copy my own answer from another thread: https://stackoverflow.com/a/72422258/1215913
async function saveToFile() {
const handle = await showSaveFilePicker({
suggestedName: 'index.html',
types: [{
description: 'HTML',
accept: {'text/html': ['.html']},
}]
});
const writable = await handle.createWritable();
await writable.write(document.body.parentNode.innerHTML);
writable.close();
}; saveToFile();
for more info check the source answer
I had done this before but was stuck and couldn't seem to find the documentation anywhere. My scenario was I had a react js SPA and needed to create a static build to run without a server (through an organisations SharePoint using a static doc repository).
It is pretty simple in the end, run
npm run build
in your project directory and it will create the static build in a 'build' folder ready for you to dump wherever needed.
Reference: https://create-react-app.dev/docs/production-build/