WEBVTT

1
00:00:01.639 --> 00:00:07.780
So as I mentioned before, I'm not 100% happy with the code that has been added here to

2
00:00:07.780 --> 00:00:08.500
app.js.

3
00:00:09.340 --> 00:00:16.079
Whilst we could run this code like this, I would rather run this code after we started

4
00:00:16.079 --> 00:00:17.440
the server.

5
00:00:18.640 --> 00:00:24.600
So what I'll do instead, instead of exporting the app object here, is I'll call app.listen,

6
00:00:24.740 --> 00:00:29.100
which we'll need to do at some point anyways, since this is the actual command that will

7
00:00:29.000 --> 00:00:30.180
start the server.

8
00:00:31.839 --> 00:00:37.360
And then it's here in this callback, as this is called, which is passed as a second

9
00:00:37.360 --> 00:00:42.960
argument to the listen method, it's in here where I actually want to initialize my database.

10
00:00:43.780 --> 00:00:48.160
So I'll cut the code from up here and instead put that in here.

11
00:00:49.480 --> 00:00:53.880
And I'll still exit the server and this process if this fails.

12
00:00:55.500 --> 00:00:59.660
But I want to do this after I started the server, so that if starting the server failed,

13
00:00:59.920 --> 00:01:02.520
I don't even try to initialize the database.

14
00:01:03.860 --> 00:01:06.480
Now here for the port, I'll also make some changes.

15
00:01:06.840 --> 00:01:12.780
Instead of always using 3000, I'll add some alternative code, the one which is suggested

16
00:01:12.780 --> 00:01:19.860
to me here now and which I can accept with a tab, like this, to take a look at the environment

17
00:01:19.900 --> 00:01:25.520
variables that have been set for this app and use the value stored in a port environment

18
00:01:25.520 --> 00:01:29.200
variable, if it's available, instead of 3000.

19
00:01:31.000 --> 00:01:37.940
And actually for that, I'll invert this and use this value as a fallback value if this

20
00:01:37.940 --> 00:01:38.800
should not be set.

21
00:01:39.800 --> 00:01:40.020
Okay.

22
00:01:41.920 --> 00:01:43.080
So that's that.

23
00:01:43.520 --> 00:01:48.680
Therefore, I'll also hit tab again and accept these changes to this string where it outputs

24
00:01:48.700 --> 00:01:51.620
the actual port if it's not the 3001.

25
00:01:53.140 --> 00:01:58.040
And with that, I'm happy with this code here in app.js, at least for now.

26
00:01:59.700 --> 00:02:02.540
We are initializing the database once the server started.

27
00:02:02.740 --> 00:02:05.340
We're handling requests to slash users.

28
00:02:06.440 --> 00:02:11.280
We're sending them to our user routes and in there, we're trying to invoke functions

29
00:02:11.300 --> 00:02:19.420
the user's controller.js file, where then in turn, we try to use the create user function,

30
00:02:19.560 --> 00:02:24.760
which is coming from the user model file, where we are indeed using the database to

31
00:02:24.760 --> 00:02:26.760
insert users, for example.

