mardi 8 septembre 2020

Design Pattern for Typescript library

I would like to develop a javascript/typescript library that work like this:

import mylibrary from 'mylibrary'

mylibrary.config({
  token: 'myRandomString'
})

mylibrary.users.get({
  id: 'userIdString'
})

mylibrary.users.create({
  username: 'userName'
})

mylibrary.products.get({
  title: 'productTitle'
})

mylibrary.products.create({
  title: 'productTitle'
})

With config() function I will set all the data I need to make the library works. This just need to be done once.

Then inside mylibrary I have different objects with the almost the same methods, in the case above users and products.

I am trying to find the best way to implement this pattern in typescript. I don't want to instantiate a class. Is my pattern considered a Singleton?

How would you approach this pattern in typescript?

Is my library developed like this, a good idea?

const mylibrary:IMyLibray = {
  
  token: '',

  config(param:ConfigType){
    ...
  },

  users: {
    create(param:CreateTypeInput){
      ...
    }
  },

  ...
  
}

p.s.: I wanted to make a library like Stripe that can be used in the browser and on the server.

Thank you

Aucun commentaire:

Enregistrer un commentaire