For this day, i focused on the justification algorithm for the endpoint /api/justify. So for now, we don’t need a unique token associated with an email to justify our text.

I put some checks in comments before the justification so i keep the logic:

export const postTextJustifyHandler = (req: Request, res: Response) => {
  console.log('The request body :', req.body);
  // check headers authorizartion bearer !null
  // check token match
  // check body content-type && !null
  if (!req.is('text/plain')) {
    res.status(400);
    throw new Error('Content-Type wrong format');
  }
  if (!req.body) {
    res.status(400);
    throw new Error('Body is empty');
  }
  // check rate limit -> 402
  // add words/day in db
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.write(
    JSON.stringify({
      message: `POST successful`,
    }),
  );
  res.end();
};

On this code, i returned nothing for now.

So, to respect the subject indicating that i need to return a plain/text, i did some tests to check if the return’s content-type is json or plain/text. And at this moment of the project, i had to recompile everytime i had an error so after some researching, i installed nodemon. It permits to compile directly after each changement of the files .ts.

npm install nodemon --save-dev

I also put some middleware for checking the content-type of the request headers

app.use((req: Request, res: Response, next) => {
  if (req.headers['content-type'] === 'application/json') {
    express.json()(req, res, next);
  } else if (req.headers['content-type'] === 'text/plain') {
    express.text()(req, res, next);
  } else {
    next();
  }
});

Justification text algo

I began with a max_length of 15, 80 was a big number for debugging.

To get the text justified, i had to cut at first the whole text by lines of length 15 characters. I splitted the text by the whitespaces, given an array of word of type string. Then i concatenated the words while taking account of their own length and the spaces we need to add. If the count of the new line was superior to 15, we don’t take the last word so we’ll keep the word for the next line.

For example :

Text : “Lorem ipsum dolor sit amet, consectetur adipiscing elit.”

I split into words[] : [Lorem] [ipsum] [dolor] [sit] [amet,] [consectetur] [asdipiscing] [elit.]

Then i concatenated them into new lines that doesn’t exceeds 15 characters, and then added those into a new tab lines[]:

lines[0]: [Lorem ipsum]

lines[1]: [dolor sit amet,]

lines[2]: [consectetur]