Skip to content

Instantly share code, notes, and snippets.

@Romakita
Last active January 31, 2020 10:38
Show Gist options
  • Save Romakita/13e408cc3bdf0460f8519f7774c92953 to your computer and use it in GitHub Desktop.
Save Romakita/13e408cc3bdf0460f8519f7774c92953 to your computer and use it in GitHub Desktop.
Wrap httpClient from atlassian-connect-express into a Ts.ED service
import {Service} from "@tsed/common"
// add all imports
export interface AtlassianRequestOptions {
headers: {
[key: string]: string;
},
[key: string]: any
}
export class AtlassianHttpClient {
constructor(app: AtlassianConnectApp, request: Express.Request) {
this.httpClient = app.getHttpClient(request);
}
get(url: string, options: Partial<AtlassianRequestOptions> = {}) {
return new Promise((resolve, reject) => {
this.httpClient.get({
url,
...reqOptions,
}, (error, response, body) => {
error ? reject(error) : resolve({response, body})
})
})
}
post(url: string, options: Partial<AtlassianRequestOptions> = {}) {
// write code for a post request
}
}
declare global {
namespace Express {
export interface Request {
atlassianHttpClient: AtlassianHttpClient
}
}
}
@Middleware()
export class CreateHttpClientMiddleware {
constructor(@AtlassianConnectApp private app: AtlassianConnectApp) {
}
use(@Req() req: Req) {
req.atlassianHttpClient = req.atlassianHttpClient || new AtlassianHttpClient(this.app, req)
}
}
import {UseBefore, Req} from "@tsed/common"
import {decoratorArgs} from "@tsed/core"
export function AtlassianHttpClientParams() {
return <T>(target: Type<any>, property: string, index: number): void => {
// Add CreateHttpClientMiddleware. This middleware will be called before the endpoint
UseBefore(CreateHttpClientMiddleware)(...decoratorArgs(target, property))
// And use the param injector. It'll pick the httpClient from req.atlassianHttpClient added by the CreateHttpClientMiddleware
Req("atlassianHttpClient")(target, property, index)
}
@Controller("/api")
export class RestApiController {
constructor(private readonly connectService: ConnectService) {}
// This does not
@Get("/info2")
@Summary("Retrieves information from the Connect App")
@Render("partials/info")
async appInfo2(@AtlassianHttpClientParams() httpClient: AtlassianHttpClient): Promise<any> {
const options = {
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
}
const {body} = await this.httpClient.get(
"/rest/atlassian-connect/latest/addons/" + this.connectService.getAppKey(),
options
);
return { "response": body }
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment