Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
satya-dev
Participant
656

Introduction:

In this blog, we'll dive into the TypeScript ecosystem using tools like @cap-js/cds-typer, cds-ts, and node-ts. This blog is divided into two parts.

To get started, we’ll create a bookshop sample project with TypeScript. You can use any IDE you prefer, such as VS Code or BAS.

Step 1: Generate the Initial Project

  1. Initialize the Project:
    Start by creating a new project directory named BookShopTyper:

 

cds init BookShopTyper

 

  • Install TypeScript Globally:
    To use TypeScript, install it globally on your system:

 

npm install -g typescript​

 

  • Add CDS Typer as a Development Dependency:
    Install the cds-typer package for TypeScript support in CAP:

 

cds add typer​

 

  • Add SQLite for Development:
    To use SQLite as your database for development, run:

 

cds add sqlite​

 

  • Add TypeScript as a Development Dependency:
    Include TypeScript in your project to enable writing .ts files:

 

npm install -D typescript​

 

  • Add ts-node for TypeScript Support in Node.js:
    Install ts-node to enable running TypeScript files directly in Node.js:

 

npm install -D ts-node​

 

After installing these dependencies, your package.json should look like this:

 

{
  "dependencies": {
    "@sap/cds": "^7",
    "express": "^4"
  },
  "devDependencies": {
    "@cap-js/cds-typer": "^0.23.0",
    "@cap-js/sqlite": "^1",
    "ts-node": "^10.9.2",
    "typescript": "^5.5.3"
  },
  "scripts": {
    "start": "cds-serve"
  }
}
​

 

Step 2: Define the Data Model

  1. Create data-model.cds File:
    Define your entities in data-model.cds:

 

using { Currency, managed, sap } from '@sap/cds/common';

namespace sap.capire.bookshop;

entity Books : managed {
  key ID   : Integer;
  title    : localized String(111)  @mandatory;
  descr    : localized String(1111);
  author   : Association to Authors @mandatory;
  genre    : Association to Genres;
  stock    : Integer;
  price    : Decimal;
  currency : Currency;
  image    : LargeBinary @Core.MediaType: 'image/png';
}

entity Authors : managed {
  key ID       : Integer;
  name         : String(111) @mandatory;
  dateOfBirth  : Date;
  dateOfDeath  : Date;
  placeOfBirth : String;
  placeOfDeath : String;
  books        : Association to many Books on books.author = $self;
}

entity Genres : sap.common.CodeList {
  key ID   : Integer;
  parent   : Association to Genres;
  children : Composition of many Genres on children.parent = $self;
}
​

 

Step 3: Define the Service
 Create book-service.cds File:

 

using { sap.capire.bookshop as my } from '../db/data-model';

service AdminService {
  entity Books as projection on my.Books;
  entity Authors as projection on my.Authors;
}

 

Step 4: Generate Type Definitions
After adding the cds-typer, you’ll notice a new folder named `@cds-models` folder & `jsconfig.json` file in the project root. This folder contains the TypeScript definitions for your CDS entities, automatically generated by the cds-typer.

Step 5: Start the Server
To start your server and watch for changes, run:

 

npm install
cds watch

 

Step 6: Add TypeScript Handlers
Create book-service.ts File:

 

import cds from '@sap/cds';
import { Request, Service } from '@sap/cds';

export default (srv: Service) => {
  srv.before('CREATE', 'Books', async (req: Request) => {
    console.log('Before creating Books');
    const { Books } = await import('#cds-models/sap/capire/bookshop');
  });

  srv.on('someAction', async (req: Request) => {
    console.log('Start someAction');
    console.log('req.data', req.data);
    let bookID = req.data.ID;
    const { Books } = cds.entities('sap.capire.bookshop');
    const books = await SELECT.from(Books).where({ 'ID': bookID });
    return books ? 'S' : 'E';
  });
};

 

Add TypeScript Configuration (tsconfig.json):
Initialize TypeScript configuration with:

 

tsc --init

 

Update tsconfig.json to look like this:

 

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "paths": {
      "#cds-models/*": ["./@cds-models/*"]
    }
  }
}

 


Step 7: Run the Application

 

cds-ts watch

 

If you encounter an error like this:

 

ERROR on server start: Cannot find module '#cds-models/sap/capire/bookshop' or its corresponding type declarations.

 

It means that the path to your model is not resolving correctly at runtime. Ensure the paths configuration in tsconfig.json points to the correct directory.

Check the complete code on GitHub: github repo 

Next: deployment............. 

 

 

Labels in this area