Skip to content

typescript interface-defined RPC abstraction with pluggable implementations (socketio / http / etc)

Notifications You must be signed in to change notification settings

devlittlemac/typescript-rpc

 
 

Repository files navigation

Typescript-RPC (FrontEnd JS <-> BackEnd nodeJS)

Basic concepts:

  1. define API

    export type EchoRequest = ToRequestType<{
      echoReq: string;
    }>;
    
    export type EchoResponse = ToResponseType<{
      echoResp: string;
    }>;
    
    export const echoAPI = createAPIDefinition<
      EchoRequest,
      EchoResponse
    >()('echo');
  2. (server - ONCE) create Server implementation instance

    const apiServer = new SocketIOSimpleAPIServer(serverSocketIO);
  3. (server) add API Handler

    apiServer.addAPI(echoAPI, async req => {
      return {
        echoResp: req.echoReq,
      };
    });
  4. (client - ONCE) create Client implementation instance

    const apiClient = new SocketIOSimpleAPIClient();
  5. (client) get API stub function

    const echo = apiClient.useAPI(echoAPI)
  6. (client) use API stub function

    const echoResponse = await echo({
      echoReq: 'test',
    })

API types:

  • simple-API: Simple request/response (see above)

  • with-progress API: API with onProgress callback

    • file uploads, etc
    export type UpdateProfileRequest = ToRequestWithProgressType<{
      username: string;
      description: string;
      profileImageFile: File;
    }>;
    
    export type UpdateProfileResponse = ToResponseType<{
      profileUrl: string;
    }>;
    
    export const updateProfileAPI = createAPIWithProgressDefinition<
      UpdateProfileRequest,
      UpdateProfileResponse
    >()('updateProfile');
    
    // client:
    const updateProfile = withProgressAPIClient.useAPI(updateProfileAPI)
    // ...later
    await updateProfile({
      username: 'a',
      description: 'b',
      profileImageFile: someFile,
      onProgress(progressEvent) {
        console.log('upload progress', progressEvent)
      }
    })
  • subscription-API: API with 'stream' callback

    • real-time notifications, etc

About

typescript interface-defined RPC abstraction with pluggable implementations (socketio / http / etc)

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 51.3%
  • TypeScript 45.4%
  • Shell 3.3%