The Server class

Again, continuing with the theme of reusing code as much as possible, we are going to use a slightly modified version of the Express Server class we wrote, way back in Chapter 4, The MEAN Stack – Building a Photo Gallery. Again, we will quickly go through the code to re-familiarize ourselves with it. First, let's put the class definition and constructor in place. Our constructor is a slimmed-down version of the constructor from Chapter 4The MEAN Stack – Building a Photo Gallery:

export abstract class Server {
constructor(private port: number = 3000, private app: any = express(), protected routingEngine: RoutingEngine = new RoutingEngine()) {}
}
}

We also want to add CORS support. While we could make this mandatory, I still like the idea that we can put control of whether we want to do this into the hands of the service developer, so we will keep this as a public method:

public WithCorsSupport(): Server {
this.app.use(cors());
return this;
}

In order for our actual server implementations to work, we need to give them the ability to add routing. We do this through the AddRouting method:

protected AddRouting(router: Router): void {
}

Now that we have our AddRouting method, we need code in place to start up our server:

public Start(): void {
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({extended:true}));
const router: Router = express.Router();
this.AddRouting(router);
this.app.use(router);
this.app.listen(this.port, ()=> console.log(`logged onto server at ${this.port}`));
}

What you may have noticed is that we are missing one important piece of the puzzle. We have no database support in place in our server, but our service needs to initialize Firebase. In our server, we add in the following:

public WithDatabase(): Server {
firebase.initializeApp(Environment.fireBase);
return this;
}

Note that I have not included Environment.fireBase in the repository because it contains details about servers and keys that I use. This is a constant that contains the Firebase connection information. You can replace this with the connection information you set up when you created your Firebase database in the cloud. To add this, you will need to create a file in the Common folder called Environment.ts which contains code that looks like this:

export const Environment = {
fireBase: {
apiKey: <<add your api key here>>,
authDomain: "advancedtypescript3-containers.firebaseapp.com",
databaseURL: "https://advancedtypescript3-containers.firebaseio.com",
projectId: "advancedtypescript3-containers",
storageBucket: "advancedtypescript3-containers.appspot.com",
messagingSenderId: <<add your sender id here>>
}
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.70.203