Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

tspace-ez-node

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

tspace-ez-node

Fast http build an API, for Node.js

  • 1.0.1
  • unpublished
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

tspace-ez-node

NPM version NPM downloads

tspace-ez-node is an api framework for node.js highly focused on providing the best developer experience.

Install

Install with npm:

npm install tspace-ez-node --save

Basic Usage

CreateServer

import { Application , Router, TContext, TNextFunction } from "tspace-ez-node";

const app = new Application()

app.get('/' , ({ res } : TContext) => {
  return res.json({
    message : 'hello world!'
  });
})

const server = app.createServer()

let port = 3000

server.listen(port , () => {
    console.log(`Server is now listening port: ${port}`);
})

server.on('error', (error: NodeJS.ErrnoException) => {
    port = Math.floor(Math.random() * 8999) + 1000
    server.listen(port)
});

// localhost:3000

Middleware

// file cat-middleware.ts
export default (ctx : TContext, next: TNextFunction) =>{
  console.log('cat middleware globals');
  return next();
}

import { Application , Router, TContext, TNextFunction } from "tspace-ez-node";
import CatMiddleware from './cat-middleware.ts'

(async () => {

  const app = new Application({
    middlewares: [ CatMiddleware ]
    // if you want to import a middleware with a directory can you follow the example
    middlewares : {
      folder : `${__dirname}/middlewares`,
      name :  /middleware\.(ts|js)$/i
    }
  })

  // or add a middleware
  app.use((ctx : TContext , next : TNextFunction) => {
    console.log('global middlewares')
    return next()
  })

  app.get('/' , ({ res } : TContext) => {
    return res.json({
      message : 'hello world!'
    });
  })

  const server = await app.createServerSync()

  let port = 3000

  server.listen(port , () => {
      console.log(`Server is now listening port: ${port}`);
  })

  server.on('error', (error: NodeJS.ErrnoException) => {
      port = Math.floor(Math.random() * 8999) + 1000
      server.listen(port)
  });

  // localhost:3000

})()

Controller

import { 
  Controller , 
  Middleware , 
  Get , 
  Post,
  PATCH,
  PUT,
  DELETE,  
  WriteHeader , 
  Query, 
  Body,
  Params,
  Cookies,
  Files, 
  StatusCode 
} from 'tspace-ez-node';

import type { 
  TCookies, TParams, 
  TRequest, TResponse ,  
  TQuery, TFiles, 
  TContext, TNextFunction
} from 'tspace-ez-node';
import CatMiddleware from './cat-middleware.ts'

// file cat-controller.ts
@Controller('/cats')
class CatController {
  @Get('/')
  @Middleware(CatMiddleware)
  @Query('test','id')
  @Cookies('name')
  public async index({ query , cookies , req } : { 
    query : TQuery<{ id : string }>
    cookies : TCookies<{ name : string}>
    req : TRequest
  }) {

    return {
      message : 'index',
      query,
      cookies
    }
  }

  @Get('/:id')
  @Middleware(CatMiddleware)
  @Params('id')
  public async indexz({ params} : TContext) {
    const id = params.id
    // find something

    return {
      params
    }
  }
}

import { Application , Router, TContext, TNextFunction } from "tspace-ez-node";
import CatController from './cat-controller.ts'

(async () => {

  const app = new Application({
    controllers: [ CatController ]
    // if you want to import a controller with a directory can you follow the example
    controllers : {
      folder : `${__dirname}/controllers`,
      name :  /middleware\.(ts|js)$/i
    }
  })

  app.get('/' , ({ res } : TContext) => {
    return res.json({
      message : 'hello world!'
    });
  })

  const server = await app.createServerSync()

  let port = 3000

  server.listen(port , () => {
      console.log(`Server is now listening port: ${port}`);
  })

  server.on('error', (error: NodeJS.ErrnoException) => {
      port = Math.floor(Math.random() * 8999) + 1000
      server.listen(port)
  });

  // localhost:3000/cats 
  // localhost:3000/cats/41

})()

Router

import { Application , Router, TContext, TNextFunction } from "tspace-ez-node";

const app = new Application()

const router = new Router()
    
router.groups('/my',(r) => {

  r.get('/cats' , ({ req , res }) => {

      return res.json({
          message : 'Hello, World!'
      })
  })

  return r
})
    
router.get('/cats' , ({ req , res }) => {
  return res.json({
      message : 'Hello, World!'
  })
})

app.useRouter(router)

app.get('/' , ({ res } : TContext) => {
  return res.json({
    message : 'hello world!'
  });
})

const server = app.createServer()

let port = 3000

server.listen(port , () => {
    console.log(`Server is now listening port: ${port}`);
})

server.on('error', (error: NodeJS.ErrnoException) => {
    port = Math.floor(Math.random() * 8999) + 1000
    server.listen(port)
});

// localhost:3000/my/cats
// localhost:3000/cats

Handlers


const app = new Application({
  logger : true, // logging
  prefixRoute : '/api' // prefix all routes in Router and Controller only!
})

app.get('/' , ({ res } : TContext) => {
  return res.json({
    message : 'hello world!'
  });
})

app.get('/errors', () => {
  throw new Error('testing Error handler')
})
    
// every response should returns following this format response
app.formatResponseHandler((results : any , statusCode : number) => {
  return {
      success : statusCode < 400,
      ...results,
      code : statusCode
  }
})
  
// every notfound page should returns following this format response
app.notFoundHandler(({ res } : TContext) => {
  return res.notFound();
})
    
// every errors page should returns following this format response
app.errorHandler((err : any , ctx : TContext) => {

  ctx.res.status(500)

  return ctx.res.json({
      success : false,
      message : err?.message,
      code    : 500
  });
}) 
    
const server = app.createServer()

let port = 3000

server.listen(port , () => {
    console.log(`Server is now listening port: ${port}`);
})

server.on('error', (error: NodeJS.ErrnoException) => {
    port = Math.floor(Math.random() * 8999) + 1000
    server.listen(port)
});

// localhost:3000/*********** // not found
// localhost:3000/errors // errors
// localhost:3000 // format response

Keywords

FAQs

Package last updated on 23 Apr 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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc