Simple CLI utils for ServiceStack projects
@servicestack/cli provides simple command-line utilities to easily Add and Update ServiceStack References for all of ServiceStack's supported languages:
typescript-ref with the URL of
typescript-ref with just a URL will save the DTOs using the Host name, you can override this by specifying a FileName as the 2nd argument:
typescript-ref with the Filename:
typescript-ref without any arguments will update all TypeScript DTOs in the current directory:
ts-ref alias instead of typescript-ref.
JsonServiceClient in the @servicestack/client npm package to make Typed API Calls.
demo.ts file with the example below using both the JsonServiceClient from the @servicestack/client npm package and the Server DTOs we want to use from our local techstacks.dtos.ts above:
ts
import { JsonServiceClient } from '@servicestack/client';
import { GetTechnology, GetTechnologyResponse } from './techstacks.dtos';
var client = new JsonServiceClient("http://techstacks.io")
let request = new GetTechnology()
request.Slug = "ServiceStack"
client.get(request)
.then(r => console.log(r.Technology.VendorUrl))
`
The JsonServiceClient is populated with the BaseUrl of the remote ServiceStack instance we wish to call. Once initialized we can send populated Request DTOs and handle
the Typed Response DTOs in Promise callbacks.
To run our TypeScript example we just need to compile it with TypeScript:
$ tsc demo.ts
Which will generate the compiled demo.js (and typescript.dtos.js) which we can then run with node:
$ node demo.js
Result:
https://servicestack.net
#### Enabling TypeScript async/await
To make API requests using TypeScript's async/await feature we'll need to create a TypeScript tsconfig.json config file that imports ES6 promises and W3C fetch definitions with:
`json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": [ "es2015", "dom" ]
}
}
`
Now we can create a new await-demo.ts file and start using TypeScript's async/await feature which as it can only be called within an async function, we'll need to wrap in an async function:
`ts
import { JsonServiceClient } from '@servicestack/client';
import { GetTechnology, GetTechnologyResponse } from './techstacks.dtos';
var client = new JsonServiceClient("http://techstacks.io")
async function main() {
let request = new GetTechnology()
request.Slug = "ServiceStack"
const response = await client.get(request)
console.log(response.Technology.VendorUrl)
}
main()
`
Now that we have a tsconfig.json we can just call tsc to compile all our TypeScript source files in our folder:
$ tsc
And then run the compiled await-demo.js` with node: