🚀 Socket Launch Week 🚀 Day 5: Introducing Socket Fix.Learn More
Socket
Sign inDemoInstall
Socket

bla

Package Overview
Dependencies
Maintainers
0
Versions
74
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

bla

Easy way to create your own API methods for server and client sides

4.0.0
latest
Source
npm
Version published
Weekly downloads
241
265.15%
Maintainers
0
Weekly downloads
 
Created
Source

bla

NPM version Build Status

Installation

npm i bla

Also you need to install runtypes to define params schema.

npm i runtypes

Quick start

Server side

Write API method declaration

import { ApiMethod } from 'bla/server';
import * as runtypes from 'runtypes';

const helloMethod = new ApiMethod({
    params: runtypes.Record({
        name: runtypes.String
    }),
    
    action: params => `Hello, ${params.name}`;
});

export default helloMethod;

Save it to api/hello.ts.

Create api with declared methods

import { ApiMethod } from 'bla/server';
import helloMethod from './api/hello.ts';

const api = new Api({
    hello: helloMethod
});

// Export api contract to use it on client side
type ApiContract = ExtractApiContract<typeof api>;

export default api;
export { ApiContract };

Save it to api.ts.

Expose api as express middleware

import * as express from 'express';
import { apiMiddleware } from 'bla/server';
import api from './api';

express()
    .use('/api', apiMiddleware({ api }))
    .listen(8080);

Client side

import { Api } from 'bla/client';
import { ApiContract } from 'pathToServer/Api.ts';

const api = new Api<ApiContract>({ url: '/api' });

api.exec('hello', { name: 'Stepan' }).then(res => {
    console.log(res); // 'Hello, Stepan'
});

FAQ

How to define both required and optional params?

Use runtypes.Intersect:

const getObject = new ApiMethod({
    params: runtypes.Intersect(
        runtypes.Record({
            id: runtypes.String
        }),
        runtypes.Partial({
            uid: runtypes.String
        })
    }),
    
    action: params => {
        // typeof `params.id` is `string`
        // typeof `params.uid` is `string | undefined`
    }
});

FAQs

Package last updated on 24 Dec 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts