We've seen how to load some data
from a local file
in our getStaticProps function.
Now I'd like to do some refactoring,
and extract that bit of logic
into its own separate module,
to follow the "separation of concerns"
design principle.
Let's start by creating a separate function
inside this file.
Let's call it "getPost".
And this function will
read the post data,
so we can just copy our existing code.
Except that here we can return
the post object directly.
So now we can call this "getPost" function
inside "getStaticProps",
and get the post object
by awaiting the Promise returned by "getPost".
We're doing a refactoring
so the functionality of our app
should stay the same,
but it's always good to check.
Now, at the moment we're always loading
the "first-post",
but we can make our "getPost" function
more general by passing
which post to load as an argument.
And then accept it as a parameter here,
that I'll call "slug",
meaning the part of the URL
that identifies a specific post.
Now we change this string
to be backtick-delimited
so that we can insert the "slug"
as a placeholder.
And let's quickly check that
we didn't break anything.
It's all good.
What I'd like to do now
is to move that function
to a separate module,
because this file is really about
rendering a page.
So the details of how to get the data
don't really belong in here.
A common approach in Next.js apps
is to have a "lib" folder
at the top-level of the project
that contains any code
that's not specific to pages
or other visual components.
So here we could create a module
called "posts",
since it will contain functions
to get the post data.
And we can simply move the function
we just wrote from the "first-post" page.
We just need to make sure to "export" it
from this module,
so we can then go and import it
in the other file,
and I'll use the auto-import feature,
so the editor automatically finds the right path.
Let's save and,
we have an error now.
That's why it's good to test the app
after every change,
so if anything breaks it's easier to fix.
In this case I simply forgot to move
the "readFile" import
into the new "posts" module,
where it's actually used.
If I save both files now,
that error should go away.
Ok, it's working again,
and that's all the refactoring
I wanted to do.
Note how this way in this file
to get the post data
we simply call the "getPost" function,
there's nothing in here
about how to get that data.
And that's a good thing,
because in this page
we're only interested in getting the data
so we can display it.
The fact that the post data
comes from a local file
is irrelevant as far as
displaying the page is concerned.
That's why it's good practice
to encapsulate that sort of logic
in a separate layer of our application,
that deals with fetching the data.