Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update type definitions and implementation to support multiple responses #1312

Merged
merged 4 commits into from Aug 1, 2023

Conversation

leorossi
Copy link
Contributor

To check it

  • Create a new platformatic service with create-platformatic
  • Add a route like this
  fastify.get('/redirect', {
    schema: {
      response: {
        302: {
          type: 'object',
          properties: {}
        },
        400: {
          type: 'object',
          properties: {
            message: { type: 'string' }
          }
        }
      }
    }
  }, 
    async (request, reply) => {
    return reply.code(302).redirect('https://google.com')
  })
  • Start the application with npm start
  • Generate frontend boilerplate files with platformatic frontend http://127.0.0.1:3042 ts
    File api-types.d.ts would include this code
interface FullResponse<T> {
  'statusCode': number;
  'headers': object;
  'body': T;
}
...
interface GetRedirectRequest {
}

interface GetRedirectResponseFound {
}

interface GetRedirectResponseBadRequest {
  'message': string;
}

export interface Api {
  setBaseUrl(newUrl: string) : void;
  getRedirect(req: GetRedirectRequest): Promise<FullResponse<GetRedirectResponseFound> | FullResponse<GetRedirectResponseBadRequest>>;
}

The implementation file api.ts would include this snippet

export const getRedirect: Api['getRedirect'] = async (request) => {
  const response = await fetch(`${baseUrl}/redirect?${new URLSearchParams(Object.entries(request || {})).toString()}`)

  let body = await response.text()

  try {
    body = JSON.parse(await response.json())
  }
  catch (err) {
    // do nothing and keep original body
  }

  return {
    statusCode: response.status,
    headers: response.headers,
    body
  }
}

@leorossi leorossi requested a review from mcollina July 28, 2023 10:12
@mcollina
Copy link
Member

Could you add a test?

Copy link
Member

@mcollina mcollina left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Signed-off-by: Leonardo Rossi <leonardo.rossi@gmail.com>
Signed-off-by: Leonardo Rossi <leonardo.rossi@gmail.com>
Signed-off-by: Leonardo Rossi <leonardo.rossi@gmail.com>
Signed-off-by: Leonardo Rossi <leonardo.rossi@gmail.com>
@leorossi leorossi merged commit e9a7852 into main Aug 1, 2023
78 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants