How can I set up multiple GET endpoints within a single server.js file using SvelteKit?

Show me a similar example of what I'm attempting to accomplish. Is there a way to achieve this in SvelteKit without having to create an additional file just for the "GET_2" endpoint?

// +server.ts
export const GET: RequestHandler = async () => {
  // ...actions
};


export const GET_2: RequestHandler = async () => {
  // ...actions
};

Answer №1

As far as I know, it is not feasible to achieve that. The documentation on using the +server command specifically mentions that handlers can be exported for HTTP methods like GET, POST, PATCH, PUT, and DELETE.

A potential workaround could involve utilizing query parameters and then directing the flow to corresponding functions within the file.

Answer №2

Although this question may be considered old, I have a workaround that I personally utilize. By having one GET method and executing different methods based on the parameters sent to it, you can achieve the desired functionality. Here are some examples of fetch calls:

// Fetch to hit get1
async function getReport1() {
        const response = await fetch(`/api/delayreports?get=1`, {
            method: 'GET'
        });
    }

// Fetch to hit get2
async function getReport2() {
        const response = await fetch(`/api/delayreports?get=2`, {
            method: 'GET'
        });
    }

Subsequently, consider the server endpoint logic:

export async function GET({ url }) {

    const get = url.searchParams.get('get')

    if (get === 1) {
        console.log('you hit get 1')
    }
    if (get === 2) {
        console.log('you hit get 2')
    }
}

This approach allows for flexibility with various parameters. Personally, I often use an ID parameter; if the ID is not null, then execute function A, otherwise execute function B.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating an object in TypeScript: the right approach

Curious if there might be a bug in TypeScript? Just seeking clarification on whether my code is incorrect or if there is an actual issue with the language. interface Something { key1: string; key2: number; key3: boolean; } const someObject: S ...

Utilize Angular to create a clickable text that sends a value back to the page for resubmission

Imagine a scenario where a page contains a submit button. Once the value of this button is retrieved, an API call is made to display some text (for example, "Name"). Now, here's what I would like to achieve: Convert the displayed text ("Name") into a ...

The Angular component route is not refreshed, terminated, and reloaded

Encountered an issue with Angular 2+ related to loading a component, navigating to another route, and then reloading the component. The code below loads an array that is then displayed using ngFor. this.sub = this.subjectsService.getAllSubjects().subscri ...

Having trouble with Visual Studio 2015 not compiling TypeScript within an ASP.NET Core project?

Seeking assistance with my Angular app development setup in VS2015. Even though it is recognized as a TypeScript Virtual Project, I am facing issues getting the transpiled files into the wwwroot folder within my ASP.NET Core project. Here's an overvie ...

The Sanity npm package encounters a type error during the build process

Recently, I encountered an issue with my Next.js blog using next-sanity. After updating all npm packages, I found that running npm run build resulted in a type error within one of the dependencies: ./node_modules/@sanity/types/lib/dts/src/index.d.ts:756:3 ...

What is the process for upgrading TypeScript to the latest version?

Is there a way to upgrade TypeScript version for ASP.net MV5 project in Visual Studio 2015? I attempted searching through Nuget but couldn't locate it. There seems to be an issue with the razor intellisense (index.d.ts file) and I'm hoping that ...

Exploring function overloading in Typescript using custom types

I encountered an issue here that I believe has 2 possible solutions. Let's start with my initial implementation using function overloading: type PostgresConnectionOptions = { dialect: "postgres"; config: pg.PoolConfig; }; type MysqlConne ...

Dealing with "Cannot find name" errors in Typescript when working with React components

I'm currently in the process of transitioning my React code to TypeScript, and I've encountered numerous challenges. One recurring issue is the "Cannot find name" errors that pop up when converting my .js files to .ts files. Let's take a lo ...

Module Not Found Error: Electron and Typescript Collaboration

I am currently facing an issue while attempting to build my electron application using typescript generated from the electron-quick-start-typescript project. I have included an additional module named auth.ts, but unfortunately, it is not being recognized ...

Guide on Implementing jQuery Plugin with Vue, Webpack, and Typescript

I am currently exploring the integration of the jQuery Plugin Chosen into my vue.js/Webpack project with TypeScript. After some research, I discovered that it is recommended to encapsulate the plugin within a custom Vue component. To kick things off, I m ...

Struggles with deducing argument types in Typescript

I'm struggling to comprehend an inference error. The ts linter highlights (event: E) within useCallback with the following message. When I cast the callback of useCallback with as T, the linter message disappears. Is there a way to avoid this workarou ...

React modal not closing when clicking outside the modal in Bootstrap

I recently utilized a react-bootstrap modal to display notifications in my React project. While the modal functions correctly, I encountered an issue where it would not close when clicking outside of the modal. Here is the code for the modal: import Reac ...

Using TypeScript with GraphQL Fetch: A Guide

I came across a similar question that almost solved my issue, but it didn't quite work for me because the endpoint I'm using is a graphQL endpoint with an additional nested property called query. For instance, if my query looks like this: const q ...

What is the best way to transfer my static files to the desired output directory in a TypeScript Express application?

I am attempting to transfer my static files from the input directory to the output directory using Express. I found guidance in this tutorial, which utilized shell.js for copying static files. The code responsible for this operation is located in CopyAsse ...

`Switching from Fetch to Axios: A step-by-step guide`

Currently in the process of refactoring some code and need to transition from using fetch to axios. Here's the original code snippet: const createAttachment = async (formData: FormData): Promise<boolean | string> => { try { const respon ...

Dealing with Angular can be frustrating at times, especially when you encounter errors like "TypeError: Cannot

Encountering an Error Message... ERROR TypeError: Cannot read properties of undefined (reading 'geoCoord') at Object.next (customers.service.ts:16:38) When assigning fixed values to "lon" and "lat" variables, like 51.1634 and 10.4477, the f ...

The attribute cannot be found within the string or object typescript

Encountering the error: Property 'p' does not exist on type 'string | { p: string; }'. Can someone assist me in resolving this issue? interface x{ n:string | {p:string} } function text(args:x){ const {n:{p}}=args; console.l ...

Inquiring about Vue 3 with TypeScript and Enhancing Types for Compatibility with Plugins

I've been struggling to find a working example of how to implement type augmentation with Vue3 and TypeScript. I have searched for hours without success, trying to adapt the Vue2 documentation for Vue3. It appears that the Vue object in the vue-class ...

Tips for saving the parameter of a function for later use within nested functions

My NodeJS (Typescript) code structure is as follows: private grandMotherFunction(arg1: MyObject, arg2: any){ ... aClass.motherFunction(arg1) ... } The aClass.motherFunction function is defined as: private motherFunction(arg1: MyObject){ ... otherClass. ...

Retrieve Data using Axios and Save in Interface with Multiple Arrays in TypeScript

Hey everyone, I'm facing an issue when trying to make a GET request using Axios through an API. When I try to assign the selected data from Axios to the userDetail interface, it gives me an error. Please take a look at the Code Sandbox where I have in ...