Skip to content

Commit

Permalink
Generate header mappers and models (Azure#561)
Browse files Browse the repository at this point in the history
* Generate header mappers and models

* Add description to header

* Honor model description if availablew
  • Loading branch information
joheredi authored Feb 7, 2020
1 parent a8e07f3 commit 3785eb3
Show file tree
Hide file tree
Showing 19 changed files with 1,639 additions and 9 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"generate-bodystring": "autorest-beta --add-credentials=false --typescript --output-folder=./test/integration/generated/bodyString --use=. --title=BodyStringClient --input-file=node_modules/@microsoft.azure/autorest.testserver/swagger/body-string.json --package-name=bodyString --package-version=1.0.0-preview1",
"generate-bodycomplex": "autorest-beta --add-credentials=false --typescript --output-folder=./test/integration/generated/bodyComplex --use=. --title=BodyComplexClient --input-file=node_modules/@microsoft.azure/autorest.testserver/swagger/body-complex.json --package-name=bodyString --package-version=1.0.0-preview1",
"generate-url": "autorest-beta --add-credentials=false --typescript --output-folder=./test/integration/generated/url --use=. --title=UrlClient --input-file=node_modules/@microsoft.azure/autorest.testserver/swagger/url.json --package-name=url --package-version=1.0.0-preview1",
"generate-customurl": "autorest-beta --add-credentials=false --typescript --output-folder=./test/integration/generated/customUrl --use=. --title=CustomUrlClient --input-file=node_modules/@microsoft.azure/autorest.testserver/swagger/custom-baseUrl.json --package-name=custom-url --package-version=1.0.0-preview1"
"generate-customurl": "autorest-beta --add-credentials=false --typescript --output-folder=./test/integration/generated/customUrl --use=. --title=CustomUrlClient --input-file=node_modules/@microsoft.azure/autorest.testserver/swagger/custom-baseUrl.json --package-name=custom-url --package-version=1.0.0-preview1",
"generate-header": "autorest-beta --add-credentials=false --typescript --output-folder=./test/integration/generated/header --use=. --title=HeaderClient --input-file=node_modules/@microsoft.azure/autorest.testserver/swagger/header.json --package-name=header --package-version=1.0.0-preview1"
},
"files": [
"dist/**",
Expand Down
8 changes: 5 additions & 3 deletions src/transforms/mapperTransforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
import { getLanguageMetadata } from "../utils/languageHelpers";
import { isNil } from "lodash";
import { normalizeName, NameType } from "../utils/nameUtils";
import { extractHeaders } from "../utils/extractHeaders";

interface PipelineValue {
schema: Schema;
Expand Down Expand Up @@ -72,9 +73,10 @@ export async function transformMappers(
return [];
}

return codeModel.schemas.objects.map(objectSchema =>
transformMapper({ schema: objectSchema })
);
return [
...codeModel.schemas.objects,
...extractHeaders(codeModel.operationGroups)
].map(objectSchema => transformMapper({ schema: objectSchema }));
}

/**
Expand Down
8 changes: 6 additions & 2 deletions src/transforms/objectTransforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,15 @@ import { getLanguageMetadata } from "../utils/languageHelpers";
import { normalizeName, NameType } from "../utils/nameUtils";
import { PropertyDetails } from "../models/modelDetails";
import { getTypeForSchema } from "../utils/schemaHelpers";
import { extractHeaders } from "../utils/extractHeaders";

export function transformObjects(
codeModel: CodeModel,
uberParents: ObjectDetails[]
): ObjectDetails[] {
const objectDetails = (codeModel.schemas.objects || []).map(object =>
const objectSchemas = codeModel.schemas.objects || [];
const headersSchemas = extractHeaders(codeModel.operationGroups);
const objectDetails = [...objectSchemas, ...headersSchemas].map(object =>
transformObject(object, uberParents)
);

Expand All @@ -45,7 +48,8 @@ export function transformObject(
kind,
name,
serializedName: metadata.serializedName,
description: `An interface representing ${metadata.name}.`,
description:
metadata.description || `An interface representing ${metadata.name}.`,
schema,
properties: schema.properties
? schema.properties.map(prop => transformProperty(prop))
Expand Down
3 changes: 0 additions & 3 deletions src/transforms/operationTransforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,6 @@ export function transformOperationSpec(
headerParameters
} = getGroupedParameters(parameters, operationFullName);

if (headerParameters && headerParameters.length) {
throw new Error(`${JSON.stringify(headerParameters)}`);
}
return {
...httpInfo,
responses: extractSpecResponses(operationDetails),
Expand Down
22 changes: 22 additions & 0 deletions src/utils/extractHeaders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { OperationGroup, ObjectSchema } from "@azure-tools/codemodel";
import { getOperationFullName } from "./nameUtils";
import { headersToSchema } from "./headersToSchema";

export function extractHeaders(operationGroups: OperationGroup[]) {
let responseHeaders: ObjectSchema[] = [];

operationGroups.forEach(operationGroup =>
operationGroup.operations.forEach(operation =>
operation.responses?.forEach(response => {
const operationName = getOperationFullName(operationGroup, operation);
const headers = response.protocol.http?.headers;
if (headers) {
const headerSchema = headersToSchema(headers, operationName);
headerSchema && responseHeaders.push(headerSchema);
}
})
)
);

return responseHeaders;
}
28 changes: 28 additions & 0 deletions src/utils/headersToSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { HttpHeader, ObjectSchema, Property } from "@azure-tools/codemodel";
import { getLanguageMetadata } from "../utils/languageHelpers";

export function headersToSchema(
headers: HttpHeader[] | undefined,
operationFullName: string
): ObjectSchema | undefined {
if (!headers || !headers.length) {
return undefined;
}

const headersSchema = new ObjectSchema(
`${operationFullName}Headers`,
`Defines headers for ${operationFullName} operation.`
);

headers.forEach(({ header, schema }) => {
if (!headersSchema.properties) {
headersSchema.properties = [];
}

const { description } = getLanguageMetadata(schema.language);

headersSchema.properties.push(new Property(header, description, schema));
});

return headersSchema;
}
21 changes: 21 additions & 0 deletions src/utils/nameUtils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { Operation, OperationGroup } from "@azure-tools/codemodel";
import { getLanguageMetadata } from "./languageHelpers";
import { TOPLEVEL_OPERATIONGROUP } from "../transforms/constants";

const ReservedModelNames = ["Error"];

export enum CasingConvention {
Expand Down Expand Up @@ -70,3 +74,20 @@ function getNameParts(name: string) {

return parts.length > 0 ? parts : [name];
}

export function getOperationFullName(
operationGroup: OperationGroup,
operation: Operation
) {
const groupName = normalizeName(
getLanguageMetadata(operationGroup.language).name ||
TOPLEVEL_OPERATIONGROUP,
NameType.Property
);
const operationName = normalizeName(
getLanguageMetadata(operation.language).name,
NameType.Property
);

return `${groupName}_${operationName}`;
}
21 changes: 21 additions & 0 deletions test/integration/generated/header/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2020 Microsoft

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
27 changes: 27 additions & 0 deletions test/integration/generated/header/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
## Azure HeaderClient SDK for JavaScript

This package contains an isomorphic SDK for HeaderClient.

### Currently supported environments

- Node.js version 8.x.x or higher
- Browser JavaScript

### How to Install

```bash
npm install header
```

### How to use

#### Sample code

Refer the sample code in the [azure-sdk-for-js-samples](https://github.com/Azure/azure-sdk-for-js-samples) repository.

## Related projects

- [Microsoft Azure SDK for Javascript](https://github.com/Azure/azure-sdk-for-js)


![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fcdn%2Farm-cdn%2FREADME.png)
46 changes: 46 additions & 0 deletions test/integration/generated/header/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"name": "header",
"author": "Microsoft Corporation",
"description": "Test Infrastructure for AutoRest",
"version": "1.0.0-preview1",
"dependencies": { "@azure/core-http": "^1.0.0", "tslib": "^1.9.3" },
"keywords": ["node", "azure", "typescript", "browser", "isomorphic"],
"license": "MIT",
"main": "./dist/header.js",
"module": "./esm/headerClient.js",
"types": "./esm/headerClient.d.ts",
"devDependencies": {
"typescript": "^3.1.1",
"rollup": "^0.66.2",
"rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-sourcemaps": "^0.4.2",
"uglify-js": "^3.4.9"
},
"homepage": "https://github.com/Azure/azure-sdk-for-js",
"repository": {
"type": "git",
"url": "https://github.com/Azure/azure-sdk-for-js.git"
},
"bugs": { "url": "https://github.com/Azure/azure-sdk-for-js/issues" },
"files": [
"dist/**/*.js",
"dist/**/*.js.map",
"dist/**/*.d.ts",
"dist/**/*.d.ts.map",
"esm/**/*.js",
"esm/**/*.js.map",
"esm/**/*.d.ts",
"esm/**/*.d.ts.map",
"src/**/*.ts",
"README.md",
"rollup.config.js",
"tsconfig.json"
],
"scripts": {
"build": "tsc && rollup -c rollup.config.js && npm run minify",
"minify": "uglifyjs -c -m --comments --source-map \"content='./dist/header.js.map'\" -o ./dist/header.min.js ./dist/header.js",
"prepack": "npm install && npm run build"
},
"sideEffects": false,
"autoPublish": true
}
39 changes: 39 additions & 0 deletions test/integration/generated/header/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/

import rollup from "rollup";
import nodeResolve from "rollup-plugin-node-resolve";
import sourcemaps from "rollup-plugin-sourcemaps";

/**
* @type {rollup.RollupFileOptions}
*/
const config = {
input: "./esm/headerClient.js",
external: ["@azure/core-http", "@azure/core-arm"],
output: {
file: "./dist/header.js",
format: "umd",
name: "Header",
sourcemap: true,
globals: {
"@azure/core-http": "coreHttp",
"@azure/core-arm": "coreArm"
},
banner: `/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/ `
},
plugins: [nodeResolve({ module: true }), sourcemaps()]
};

export default config;
35 changes: 35 additions & 0 deletions test/integration/generated/header/src/headerClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/

import * as operations from "./operations";
import * as Models from "./models";
import * as Mappers from "./models/mappers";
import { HeaderClientContext } from "./headerClientContext";

class HeaderClient extends HeaderClientContext {
/**
* Initializes a new instance of the HeaderClient class.
* @param options The parameter options
*/
constructor(options?: any) {
super(options);
this.header = new operations.Header(this);
}

header: operations.Header;
}

// Operation Specifications

export {
HeaderClient,
HeaderClientContext,
Models as HeaderModels,
Mappers as HeaderMappers
};
export * from "./operations";
41 changes: 41 additions & 0 deletions test/integration/generated/header/src/headerClientContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/

import * as coreHttp from "@azure/core-http";

const packageName = "header";
const packageVersion = "1.0.0-preview1";

export class HeaderClientContext extends coreHttp.ServiceClient {
$host: string;

/**
* Initializes a new instance of the HeaderClientContext class.
* @param options The parameter options
*/
constructor(options?: any) {
// Initializing default values for options
if (!options) {
options = {};
}

if (!options.userAgent) {
const defaultUserAgent = coreHttp.getDefaultUserAgentValue();
options.userAgent = `${packageName}/${packageVersion} ${defaultUserAgent}`;
}

super(undefined, options);

this.requestContentType = "application/json; charset=utf-8";

this.baseUri = options.baseUri || "{$host}";

// Assigning values to Constant parameters
this.$host = options.$host || "http://localhost:3000";
}
}
Loading

0 comments on commit 3785eb3

Please sign in to comment.