Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
3.5 kB
5
Indexable
Never
const generateToken = () => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let token = '';

  for (let i = 0; i < 16; i += 1) {
    token += characters.charAt(Math.floor(Math.random() * characters.length));
  }

  return token;
};
// Verifica se o token é válido ou está presente nas requisições
const tokenValid = (request, response, next) => {
  const { authorization } = request.headers;

  if (!authorization) {
    return response.status(NOT_FOUND_TOKEN).json({ message: 'Token não encontrado' }); 
  }
  if (authorization.length !== 16 || typeof authorization !== 'string') {
    return response.status(NOT_FOUND_TOKEN).json({ message: 'Token inválido' }); 
  }
  
  next();
};
app.get('/talker/search', tokenValid, async (request, response) => {
  const { q } = request.query;
  const talkers = await fs.readFile(path.join(__dirname, ARQUIVO), 'utf-8');
  const talkersJson = JSON.parse(talkers);
  const talkerFind = talkersJson.filter((talker) => talker.name.includes(q));
  if (!talkerFind) {
    return response.status(NOT_FOUND_TOKEN)
      .json({ message: 'Pessoa palestrante não encontrada' }); 
  } 
  if (typeof q === 'undefined') {
    return response.status(HTTP_OK_STATUS).json(talkersJson);
  }
  
  return response.status(200).json(talkerFind);
});

app.post('/talker', 
  tokenValid, 
  async (request, response) => {
    const { name, age, talk } = request.body;
    const talkers = await fs.readFile(path.join(__dirname, ARQUIVO), 'utf-8');
    const talkersJson = JSON.parse(talkers);

    const newTalker = {
      name, age, talk, id: talkersJson.length + 1,
    };
    const valid = validTalker(newTalker);
    if (valid.message) {
      return response.status(400).json({ message: valid.message });
    }

    talkersJson.push(newTalker);
    await fs.writeFile(path.join(__dirname, ARQUIVO), JSON.stringify(talkersJson));

    return response.status(201).json(newTalker);
  });

app.get('/talker', async (_request, response) => {
  const talkers = await fs.readFile(path.join(__dirname, ARQUIVO), 'utf-8');
  const talkersJson = JSON.parse(talkers);

  if (!talkersJson) return response.status(200).json([]);

  return response.status(200).json(talkersJson);
});

app.get('/talker/:id', async (request, response) => {
  const { id } = request.params;
  const talkers = await fs.readFile(path.join(__dirname, ARQUIVO), 'utf-8');
  const talkersJson = JSON.parse(talkers);

  if (!talkersJson) return response.status(200).json([]);
  const talkerFind = talkersJson.find((talker) => talker.id === +id);
  if (!talkerFind) {
    return response.status(404).json(
      { message: 'Pessoa palestrante não encontrada' },
    ); 
  }
  return response.status(200).json(talkerFind);
});

//  Verifica o email e a senha para realizar o login
app.post('/login', (request, response) => {
  const { email, password } = request.body;
  if (!email) {
    return response.status(400).json({ message: 'O campo "email" é obrigatório' });
  }
  if (!password) {
    return response.status(400).json({ message: 'O campo "password" é obrigatório' });
  }
  if (password.length < 6) {
    return response.status(400).json({ message: 'O "password" deve ter pelo menos 6 caracteres' });
  }
  const regexEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!regexEmail.test(email)) {
    return response.status(400).json({ message: 'O "email" deve ter o formato "email@email.com"' });
  }
  return response.status(200).json({ token: generateToken() });
});
Leave a Comment