Skip to content

Instantly share code, notes, and snippets.

@adegbengaagoro
Last active August 3, 2022 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adegbengaagoro/f2aa73cc3aeb1195e64e20552b5c9f7b to your computer and use it in GitHub Desktop.
Save adegbengaagoro/f2aa73cc3aeb1195e64e20552b5c9f7b to your computer and use it in GitHub Desktop.
How to structure the Service Classes to be used in the MVCS pattern

Service Class Structure

The idea is to have a set of consistent methods that are exposed from the service, the service is a class with static methods.

Generic Methods

getXById
getXByIdentifier
getXBySlug
getX
getXId
createXRecord
updateXRecord
listActiveXRecord
listDisabledXRecord
deleteXRecord
checkIfXExists

Where X = ModelName for example User, UserRole, Transaction etc.

Variants e.g. UserService

getUserByEmail
getUserByMobileNumber

<All Generic Methods />

In the scenario where the aforementioned list don't match and a new one needs to be created, the ModelName must be in the method name e.g. getUserFullName()

Default Text Generators

If the Model has data that could be used as a check tool within the code-base, we create output functions that output the value instead of defining a variable that holds the string to check in order to get the value.

This works really well when you need to use an object's slug to perform an action. Instead of hard-coding the slug, you write an output function that returns the slug so you can pass that function to your task e.g.

You want to get the ID for a particular user role, the best input is the slug of that user role, the code below shows the example of using the service where there is an output method.

const getUserRoleId = await UserRoleService.getUserRoleId(String(await UserRoleService.getSystemSlug()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment