Search code examples
node.jskoa

How to call the function in backend in Node.js & koa2


I use Node.js, koa2 and ejs to build a website, and there's a function like following

in app.js

mysqOptlModel.getAllRecords()
.then(async(result) => {
   await ctx.render('AllRecordsView', {
       allrecords:result
   })
})

in list.ejs of the frontend

<% allrecords.forEach(function(item, i){%>
<tr>
  <td><%=item.username%></td>
  <td><%=item.createdtime%></td>
</tr>
<%})%>

Here are my questions

  1. I don't want to show the full username, I just want to show some parts, and some is instead by *

  2. The createdtime is timestamp format, and I want to change it to Date format

My current solution

I write two JavaScript function in list.ejs, and call them to use.

My expectation

I want to do this in app.js, not in list.ejs

Is there any ideas?


Solution

  • This could be a way to modify your result in app.js:

    mysqOptlModel.getAllRecords()
        .then(async(result) => {
    
            // here the modification happens
            modifiedResult = result.map((item) => { 
                return {
                    username: item.username.substr(0,3) + '*****', 
                    date: new Date(item.createdtime).toISOString().substr(0,10)
                }
            })
    
            await ctx.render('AllRecordsView', {
                allrecords:modifiedResult           // pass the modified result
            })
        })