npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@simpli/serialized-request

v1.0.8

Published

Make HTTP requests and serialize/deserialize the request and response to Javascript/Typescript class objects

Downloads

47

Readme

Serialized-Request

Make HTTP requests and serialize/deserialize the request and response to Javascript/Typescript class objects.

Serialized-Request uses Axios to handle HTTP calls and Class-Transformer to transform plain objects from/to class-objects

Install

npm i @simpli/serialized-request axios class-transformer

Request Usage

Serialized-Request supports GET, POST, PUT, PATCH, DELETE and HEAD Http Methods

Import

import { Request, RequestListener } from '@simpli/serialized-request'
// RequestListener is optional

Create any class for Request and Response

class BlogPost {
  id: number | null = null
  title: string | null = null
  body: string | null = null
  userId: number | null = null
}

Make a GET request with a new Object response

const respBlogPost = await Request.get('https://jsonplaceholder.typicode.com/posts/1')
      .as(BlogPost) // we are choosing to transform to a new object of BlogPost class
      .getData()

/*
respBlogPost is a BlogPost object and will be something like this:
{
  body: `quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto`,
  id: 1,
  title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  userId: 1
}
*/

Make a GET request with an Array response

const blogPosts = await Request.get('https://jsonplaceholder.typicode.com/posts')
      .asArrayOf(BlogPost) // we are choosing to transform to an array of BlogPost
      .getData()

/*
blogPosts is a BlogPost[] and will be something like this:
[
  {
    body: `quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto`,
    id: 1,
    title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    userId: 1
  },
  ...
]
*/

Make a POST request filling an existing object on response

// instantiate an object
const myBlogPost = new BlogPost()
myBlogPost.body = 'no great news today, the rich are getting richer'

// pass the object as the POST request Body
await Request.post('https://jsonplaceholder.typicode.com/posts/', myBlogPost)
  .as(myBlogPost) // and filling its properties on response, PS.: it could be a different object
  .getData()

/* myBlogPost is a BlogPost with the properties filled:
{
  id: 101, // this id was filled by the server response
  body: 'no great news today, the rich are getting richer',
  title: null,
  userId: null
}
*/

Response types

You can use this methods to parse the response:

  • as(MyClass) - Transforms to a new object of the choosen class
  • as(myInstantiatedObject) - Fills the properties of the choosen object
  • asArrayOf(MyClass) - Transforms to an array of the choosen class
  • asString() - Returns as string
  • asNumber() - Returns as number
  • asBoolean() - Returns as boolean
  • asAny() - Returns as it is
  • asVoid() - Returns nothing

Retrive the Response information

const resp = await Request.delete('https://jsonplaceholder.typicode.com/posts/1')
  .asVoid()
  .getResponse()

// if successful, resp.status will be 200
// and resp.data will be the response body (use getData() as shortcut)

Add a delay before the request

const resp = await Request.head('https://jsonplaceholder.typicode.com/posts/1')
  .delay(2000) // wait 2 seconds before making the request
  .asString()
  .getResponse()

Globally listen to requests

Useful for loading interactions

// on this example we are setting counters for when the request start and end
let startCbCount = 0
let endCbCount = 0
const startCb = (requestName: string) => startCbCount++
const endCb = (requestName: string) => endCbCount++

// then we register the listeners passing a name
RequestListener.onRequestStart(startCb)
RequestListener.onRequestEnd(endCb)

// make the request
const myBlogPost = await Request.get('https://jsonplaceholder.typicode.com/posts/1')
  .name('foo') // set the request name here
  .as(BlogPost)
  .getData()

// then the listeners will be called
// startCbCount and endCbCount are both 1 now

RequestListener.removeListener(startCb) // you can remove the specific listener
RequestListener.clearListeners() // or remove all listeners of that name

Listeners can use the endpoint instead of the request name aswell

Control the Serialization lifecycle

Sometimes you need to do things before and after the serialization

// You only need to implement some methods that will be called during the request
class CallbackResponsesExample {
  onBeforeResponse() {
    // a method called before everything
  }

  onBeforeSerialization() {
    // a method called just before the serialization
  }

  onAfterSerialization() {
    // a method called right after the serialization
  }
}

Ignore fields and map names and types with Annotations

Using Class-Transformer we can control the serialization behaviour

@ResponseSerialize(func) or @Type(func)

Working with nested objects

@ResponseExpose(name?) or @Expose({ name, toClassOnly: true })

Skipping depend of operation

@RequestExpose(name?) or @Expose({ name, toPlainOnly: true })

Skipping depend of operation

@HttpExpose(name?) or @Expose({ name })

Exposing properties with different names

@RequestExclude() or @Exclude({ toPlainOnly: true })

Skipping depend of operation

@ResponseExclude() or @Exclude({ toClassOnly: true })

Skipping depend of operation

@HttpExclude() or @Exclude()

Skipping specific properties