Pour encapsuler les données et comportements d'une entité de l'application, les classes permettent d'exploiter les concepts orienté-objet en JavaScript.
export class User {
constructor(username) {
this.username = username
}
}
import { User } from './User.js'
export class UserCredentials extends User {
constructor({username, password}) {
super(username)
this.password = password
}
matches(credentials) {
return this.username == credentials.username && this.password == credentials.password
}
}
Pour encapsuler la manipulation des données de l'application, ex: CRUDL, en utilisant les modules, on obtient automatiquement le comportement d'un singleton.
import { UserCredentials } from '../models/UserCredentials.js'
import { User } from '../models/User.js'
const USERS = [
new UserCredentials({ username: 'a', password: 'a' }),
new UserCredentials({ username: 'b', password: 'b' }),
new UserCredentials({ username: 'c', password: 'c' }),
]
class AuthService {
#currentUser = null // ATTENTION, à utiliser judicieusement
get currentUser() {
return this.#currentUser
}
signUp(credentials) {
const { username, password } = credentials
const user = USERS.find((u) => u.username == username)
if (!user) {
USERS.push(new UserCredentials({username, password}))
this.#currentUser = new User( username )
}
return !!this.#currentUser
}
logIn(credentials) {
const user = USERS.find((u) => u.matches(credentials))
this.#currentUser = user ? new User(user.username) : null
return !!this.#currentUser
}
logOut() {
this.#currentUser = null
}
}
const service = new AuthService()
export default service
src
├── App.js
├── components
│ ├── StyledButton.js
│ └── StyledTextInput.js
├── models
│ ├── User.js
│ └── UserCredentials.js
├── screens
│ ├── auth
│ │ ├── Login.js
│ │ └── Signup.js
│ ├── recipes
│ │ ├── RecipeItem.js
│ │ ├── Recipe.js
│ │ └── Recipes.js
│ └── Screen.js
└── services
└── Auth.js
src
├── App.js
├── auth
│ ├── Auth.service.js
│ ├── Login.js
│ ├── Signup.js
│ ├── UserCredentials.model.js
│ └── User.model.js
├── components
│ ├── Screen.js
│ ├── StyledButton.js
│ └── StyledTextInput.js
└── recipes
├── RecipeItem.js
├── Recipe.js
├── Recipe.model.js
└── Recipes.js