declarapi
Version:
Declarative API generation
57 lines (45 loc) • 2.28 kB
text/typescript
import { OutputSuccess } from '../transform/types.js'
import elasticCodeGen, { ElasticInputType } from './elastic.js'
import { name, typeDef } from './common.js'
import { kvCodeGen } from './kv.js'
export const server = (contracts: OutputSuccess[]): string => {
const valueDef = contracts.map(x => {
let handle = 'undefined'
if (x.preferredImplementation && x.preferredImplementation.type === 'elasticsearch') {
const codeGenInput:ElasticInputType = x.method === 'GET'
? { method: x.method, search: x.search || 'idOnly' }
: { method: x.method }
handle = elasticCodeGen(x.preferredImplementation, codeGenInput)
} else if (x.preferredImplementation && x.preferredImplementation.type === 'key-value') {
const codeGenInput:ElasticInputType = x.method === 'GET'
? { method: x.method, search: x.search || 'idOnly' }
: { method: x.method }
handle = kvCodeGen(x.preferredImplementation, codeGenInput)
}
return `${name(x)}: {
name: "${x.name}",
manageFields: ${JSON.stringify(x.manageFields, undefined, 2)},
authentication: ${JSON.stringify(x.authentication, undefined, 2)},
type: "${x.method}",
handle: ${handle},
arguments: ${JSON.stringify(x.arguments)} ,
returns: ${JSON.stringify(x.returns)}}`
}).join(',\n')
const contractTypeList = contracts.map(x =>
`${name(x)}: ContractType<${name(x)}Argument, ${name(x)}Returns>`).join('\n')
const elastic = contracts.find(x => x.preferredImplementation?.type === 'elasticsearch')
const kv = contracts.find(x => x.preferredImplementation?.type === 'key-value')
const elasticImport = elastic ? 'import * as elastic from "declarapi-runtime/elastic.js"\n' : ''
const kvImport = kv ? 'import * as kv from "declarapi-runtime/kv.js"\n' : ''
const result =
`/**********************************************
DO NOT EDIT THIS FILE, IT WILL BE OVERRIDDEN
***********************************************/
import { ContractType } from "declarapi-runtime"
${elasticImport}${kvImport}
${typeDef(contracts)}
export type ContractListType = {\n${contractTypeList}\n}\n
export const contracts: ContractListType = {\n${valueDef}\n}\n`
return result
}
export default server