
The article describes the translation of TypeScript code into OData queries during program compilation.
The babel-plugin-ts2odata plugin parses JavaScript AST using the TsToOdata library , the description of which in my previous article, Typed OData queries in TypeScript .
The disadvantage of the first version of the TsToOdata library was the presence of dependencies on packages babel/ parser, babel/ traverse, parsing JavaScript code at runtime was also quite expensive. Now these dependencies and code parsing are made in a separate ts2odata-babel package . For development, you can use the ts2odata package which has devDependencies on ts2odata-babel and performs translation of requests at runtime, and for release you can use the assembly with a plug-in that will do all the work during compilation of your project. As a result of the plugin, your program will have only two dependencies on the ts2odata and cross-fetch packages .
To get started, you need to install the packages:
npm install --save-dev @babel/core @babel/cli
npm install ts2odata
npm install --save-dev babel-plugin-ts2odata
Add the babel.config.js file to the project root:
module.exports = {
plugins: [
[
'babel-plugin-ts2odata',
{
odataNamespace: 'OdataToEntity.Test.Model'
}
]
]
};
the odataNamespace key is necessary for the correct translation of requests if your OData service does not support enumerations without a namespace (Namespace).
scripts package.json:
"build": "tsc --build && npx babel ./source --out-dir ./lib"
source TypeScript, lib JavaScript .
TypeScript:
let price = 2.1;
let orders = context.Orders.filter(o => o.Items.every(i => i.Price >= price), { price })
.select(i => { return { orderYear: i.Date.getFullYear() } }).toArrayAsync();
:
let price = 2.1;
let orders = context.Orders.filter("Items/all(d:d/Price ge {price})", {
price
}).select("[{\"expression\":\"year(Date)\",\"alias\":\"orderYear\",\"kind\":1}]").toArrayAsync();
OData :
http://localhost:5000/Orders?$filter=Items/all(d:d/Price+ge+2.1)&$compute=year(Date)+as+orderYear
, code.js QueryTests.ts, output.js .
vue.js.
TypeScript, , , - .