cancel
Showing results for 
Search instead for 
Did you mean: 

SAP CAP - How to create a custom endpoint?

emorales
Explorer
0 Kudos
145
  • SAP Managed Tags:

I would like to improve my CAP service by adding custom endpoints with business logic.

I don't know how to do it correctly, I'm calling the created endpoint but it's not returning anything to me. I am sharing my implementation with you to see if you can help me. I just want to try something basic, like being able to get an object/entity using an ID sent by parameter.

entities_srv.cds:

using { app.entities } from '../db/entities';

service BTP6SService
{
    @requires: 'Admin'
    entity EMPRESA as
        projection on entities.EMPRESA;

    @requires: 'Admin'
    entity PERSONA as
        projection on entities.PERSONA;

    @requires: 'Admin'
    entity AREANIVEL as
        projection on entities.AREANIVEL;

    @requires: 'Admin'
    entity AREA as
        projection on entities.AREA;

    @requires: 'Admin'
    entity SECTOR as
        projection on entities.SECTOR;

    @requires: 'Admin'
    entity EQUIPO as
        projection on entities.EQUIPO;

    @requires: 'Admin'
    entity TIPORESPUESTA as
        projection on entities.TIPORESPUESTA;

    @requires: 'Admin'
    entity CUESTIONARIO as
        projection on entities.CUESTIONARIO;

    @requires: 'Admin'
    entity PREGUNTA as
        projection on entities.PREGUNTA;

    @requires: 'Admin'
    entity VISITA as
        projection on entities.VISITA;

    @requires: 'Admin'
    entity VISITACUESTIONARIO as
        projection on entities.VISITACUESTIONARIO;

    @requires: 'Admin'
    entity VISITACUESTIONARIOPREGUNTA as
        projection on entities.VISITACUESTIONARIOPREGUNTA;

    @requires: 'Visitante'
    entity NOTICIA as
        projection on entities.NOTICIA;

    @requires: 'Visitante'
    entity NOTICIAMEDIA as
        projection on entities.NOTICIAMEDIA;

    @requires: 'Visitante'
    entity NOTICIAPERSONALIKE as
        projection on entities.NOTICIAPERSONALIKE;

    action getEmpresaById(id: String) returns EMPRESA;
}

annotate BTP6SService with @requires :
[
    'authenticated-user'
];

server.js:

"use strict";

const cds = require("@sap/cds");

const cors = require("cors");

const { SELECT } = cds.ql;

cds.on("bootstrap", app => app.use(cors()));

cds.on("ready", () => {
    const { BTP6SService } = cds.services;

    BTP6SService.on("getEmpresaById", async (req) => {
        const id = req.data.id;

        const empresas = await cds.run(SELECT.from("entities.EMPRESA").where({ ID: id }));

        if (empresas.length === 0) {
            req.error(404, `Empresa con ID ${id} no encontrada.`);
        }

        return empresas[0];
    });
});

module.exports = cds.server;

This is how I am calling the endpoint in my React Native app, definition and usage:

const getEmpresaById = async (id, token) => {
    try {
      const response = await axios.post(
        "https://769f798etrial-emorales-ebwzszn2-dev-btp6s-srv.cfapps.us10-001.hana.ondemand.com/odata/v4/btp6-s/getEmpresaById",
        { id: id },
        {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
            "x-requested-with": "XMLHttpRequest",
          },
        }
      );

      // Procesa la respuesta
      console.log(response.data);
      return response.data;
    } catch (error) {
      console.error("Error al obtener la empresa:", error);
      throw error;
    }
  };
getEmpresaById("8d7a5b2e-4c9f-3e6a-9d2b-5f1e7a3c6b9d", token)
        .then((empresa) => {
          console.log("Empresa obtenida:", empresa);
        })
        .catch((error) => {
          console.error("Error:", error);
        });

Empty result:

emorales_0-1727970290829.png

View Entire Topic
WouterLemaire
Active Contributor
0 Kudos

Check this example where I have a custom implementation for the entity WordAttachments: https://github.com/lemaiwo/cap-word-template/blob/4428a25b4793034af76a30618c7c1b4d85d71ecc/srv/cat-s...