Next Js Server Side Api Read and Write JSON - javascript

I'm trying to write a basic local api for myself using Next.js, it is a timeline generator, and I am stuck at actually reading the file from the api folder.
What do I want in my local aplication:
1.A simple page where I can input an event, with a date and description
2.Open a list.json file somewhere and push that new event to that json file, writing on it.
What I am currently doing and where I am stuck:
I am aware we cant write on files on the client side, so I started looking at the api routes in next js to access the JSON file, but I cannot even manage to read it!
I have an api folder inside pages folder, and in this api folder I have two files: one is the list.json file, where I previously manually write some events with respective dates; and the other is getlist.js, with this code:
var fs = require('fs');
export default function getList(req, res) {
const rawList = fs.readFile('list.json');
var list = JSON.parse(rawList);
res.json(list);
}
Now on the pages folder I have a index.js file where I try to access this getlist.js api using getStaticProps(), like this:
import getlist from './api/getlist'
export async function getStaticProps(){
var list = getlist();
return {
props: {
list
}
}
}
I have tried using other stuff, like the fecth function, to get to getlist.js, but nothing I do seems to work.
Can anyone help me?
And since I'm already in here, how would I manage to get the input from the form I already have in my client side page and write it to that list.json file in my api folder?

There are two ways how you can read json in next.js:
Import inside getStaticProps [https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation]
export async function getStaticProps(context){
const example = await import('./api/example.json');
return {props: {example: example.default}}
}
Import or read in handler function inside api folder [https://nextjs.org/docs/api-routes/introduction]:
const fs = require('fs');
export default async function handler (req, res) {
const example = await fs.readFile('./example.json');
return res.status(200).json({example});
}
In order to write *.json file you need to send request with value to the server api (handler from api folder that was mentioned before).
That's how the part to write json will look like:
const fs = require('fs');
export default async function handler(req, res) {
//...
if (req.method === 'POST'){
fs.writeFileSync('./example.json', JSON.stringify(req.body))
return res.status(200).json({});
}
//...
}

Related

Next.js - API call from different page is not loading the data

Hello everyone I am extremely new at the Next.js world.
I am using the getStaticProps() to make an API call and in order to make it little organized, i have created a separate page "git" under "pages" folder and here is my code:
function Git({ stars }) {
return <div>Next stars: {stars}</div>
}
export async function getStaticProps() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const json = await res.json()
return { stars: json.stargazers_count }
}
export default Git
And i am trying to load the API data to the index.js file under the "pages" folder.
Inside the index.js file, i am using below to load the API data from the "Git" page
import fetch from "isomorphic-unfetch"
import Git from './Git'
And under the following
render () {
return (
<Git />
On the browser, i am not seeing the API data but i am seeing the HTML from the "Git" page
<div>Next stars: </div>
Is there any way if i can load the API data from different page to the index.js page?
However, if i directly access the page for example: http://0.0.0.0:3000/Git then i get the proper API data.
Issue
The issue is about the API data in the page "Git" is not getting passed to the main page "index.js" is there any way if i can pass the data from the "Git" to the "index.js"
I resolved it by putting the following code in the index.js file
const gitData = await Git.getInitialProps();
And that's where I want to print it out
<Git {...this.props.gitData}/>

exported object is undefined in nodejs

I am using multer in index.js and i need to use an object which has multer storage engine in other routes. So i have exported the object but the problem is when i i try to use it in the route file its undefined.
index.js
const storage = new GridFsStorage({//some config})
const upload = multer({storage})
app.use('/posts',postRouter)
//if i use the middleware upload.single('file') here, will it affect all the routes like(posts/a,posts/b)?
exports.upload = upload
postRouter.js
const index = require('../index')
setTimeout(() => {
console.log(index.upload)
}, 1000);
console.log(index.upload)
i tried using setTimeout and its giving me the expected result but outside settimmeout its undefined.
why is this happening. what is the best way to apply the multer middleware in some other routes by exporting it from index?
the problem is GridFs is taking sometime to connect and do its work, but before that this upload object is exported . thats why above scenario occurs. any idea how to avoid that?
As GridFsStorage is asynchronous, so it need some time to init. And you can just
pass upload as param to the postRouter function.
app.use('/posts', postRouter(upload))

React component that reads from a .txt file and displays data

I am trying to create a react component that reads from a .txt file with in my project and displays the text. Not sure where to start. I know how to call the component but not code for the component.
You must use a Node.js default module called fs
https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback
const fs = require("fs");
fs.readFile('myfile.txt', (err, data) => {
if (err) throw err;
// Do your stuff here
console.log(data);
});
If you are just trying to get values to pass into your React component then you can try turning it into a JSON file
and then
import data from '<path_to_json_file>';

Running Code When a Module is Loaded and Exposing It as Middleware

I am still trying to fully understand how exporting and importing modules works in Nodejs.
I am using the following file to seed a mongodb database. This file runs exactly as it should and returns exactly the result I am expecting, when I execute it as a standalone file. My issue is I want to use this file in two different places in my app. So I am trying to make it an exportable/importable module. Here is what I have tried:
seed.js looks like this:
'use strict';
// library modules
const {ObjectID} = require('mongodb');
const seeder = require('mongoose-seed');
const jwt = require('jsonwebtoken');
const util = require('util');
// local modules
const {Course} = require('./../models/course');
const {Review} = require('./../models/review');
const {User} = require('./../models/user');
const {data} = require('./../data/data.js');
const config = require('./../config/config.js');
/*==================================================
build seeding Courses, Reviews, Users
==================================================*/
// Connect to MongoDB via Mongoose
let seed = seeder.connect(process.env.MONGODB_URI, (e) => {
console.log(`Connected to: ${process.env.MONGODB_URI} and seeding files`);
// Load Mongoose models
seeder.loadModels([
'src/models/user.js',
'src/models/review.js',
'src/models/course.js'
]);
// Clear specified collections
seeder.clearModels(['User', 'Review', 'Course'], function() {
// Callback to populate DB once collections have been cleared
seeder.populateModels(data, function() {
seeder.disconnect();
});
});
});
module.exports = seed;
Within app.js I have these two lines
const seed = require('./middleware/seed');
and
app.use(seed);
I have also tried, to no avail
app.use(seed());
What is missing? I don't want to use the code in-line in two different places (DRY you know).
It is failing with this error:
throw new TypeError('app.use() requires a middleware function')
I am sorry about the formatting I thought I was using markdown, but I am clearly not.
You are executing your seeder function in that module and not returning any middleware function at all. Middleware is always a function and it has the form of:
const seed = function (req, res, next) {
...
next()
}
With what you have now, the best you can do is the following which will certainly seed your models when the module is loaded.
const seed = require('./middleware/seed');
Are you trying to run those two functions as middleware, on every request? In that case you'd do something like this:
const seed = function (req, res, next) {
seeder.connect(..., (e) => {
...
seeder.clearModels(..., ()=>{
...
next()
})
})
})
If you want to run that seeder code at the module level AND to expose it as middleware then wrap the current module level code in function and execute it when the module loads. Notice that the new function optionally handles the next callback if it receives it.
function doSeed(next){
//your code currently running at module level
if(next)
return next()
}
doSeed(); //run the code at the module level
const seed = (req, res, next) => doSeed(next))
module.exports = seed;
One way that I allow myself to have access to a variable in different instances is adding it to the process variable. In node.js no matter where in the project it is, it will always be the same. In some cases, I would do process.DB = seed(); which would allow process.DB to always be the result of that. So inside your main class you can do process.DB = seed(); and all of your other classes running off of that one main class would have access to process.DB keeping your database readily available.

Node.js | Call function from original file in imported file

I recently tried to organize my code by exporting functions into different files, so my main file stays clean. To do so I imported the other js file in my main file with
const request = require('./request.js');
In "request.js" I used export, so I can call the function in my main file. Is it is possible to call a function, that is defined in the main file, from the "request.js" file? Unfortunately I can't just return the information back to the main file, because I am using callbacks.
Yes it's possible.
You just need to export function from the main file and then import your main file inside request.js:
// main.js:
module.exports.someFunction = function() {
// Some code
};
const request = require('./request.js');
request.someRequestFunction();
// request.js
var main = require('./main.js');
module.exports = {
someRequestFunction: function() {
main.someFunction(); // Call function from main module
}
};

Categories