קורס Node.JS שיעור תרגול API


זה נושא דיון מלווה לערך המקורי ב- https://www.tocode.co.il/bundles/nodejs/lessons/34-api-lab

הי ינון,
I consider 2 options
1)
To initialize my Files object in constructor,
to build kind of dictionary with file names as keys and file content as values.
In this case GET requests are served faster, kind of cache.
2)
To read the files each time - GET is served slower yet more reliable.

yet in both cases I will need to perform actual fs actions for POST, PUT and DELETE.
What’s better?

תודה

I would not save the files in a dictionary because you’ll soon run out of memory. In many real world scenarios you wouldn’t work with file storage anyway because it doesn’t scale well.

For this exercise I think it’s best to read the file again on each request

Hi Ynon!
You remind directory duplication in exercise definition,
and I try to understand
Option 1
if it is only about files in some directory -
definitiely simplier option.
Or Option 2
or it is about directory contains both files and directories as in files explorer exercise in
https://www.tocode.co.il/bundles/nodejs/lessons/26-express-views-lab?tab=video
more complex API.

If it is option 1 with files only - I would use REST convention with /files/:name param
for file name.
If it is more complex option 2 - nested file and directory names with slashes
are possible as in files explorer exercise.
In this case I would take the query path variable option.

Thank you

Hi Ynon!
I made it the easy way by option 1 - with files in folder only.
So I used the REST convention where file name comes in req.param.name like
files/f1.txt/
files/:name/
Also I checked the API routes with curl - pretty fun.
Yet without automated testing yet - jest etc…

אודה על הערות

היי,
לגבי שאלה 2:
זה בקוד שלי בצד שרת:

    addLink(linkName) {
        let newLink;
        if(linkName!=""){
        newLink= { id: this.nextId++, linkName: linkName,liks:0}
        this.news.push(newLink);
        const data = JSON.stringify(this.news);
        fs.writeFile('links.json', data, (err) => {
             if (err) {
             console.error(err);
            return;
                    }
    console.log('Array successfully written to file.');
});
        return newLink.id;}
    }

וזה הקוד שלי בAPI:

/* POST new link*/
router.post('/', function(req, res) {
    const link = req.body.link;
    const newLinkID=links.addLink(link);   
    res.send({id:newLinkID});
});

כאשר אני מריצה בCURL אני מקבלת את זה:


אך כאשר אני מנסה לבצע שוב קריאת GET בCURL אני לא רואה שהתווסף לי הלינק, אך בקובץ הוא כן מופיע.
מדוע זה?
תודה על המענה המהיר והיעיל!