Простой и легковесный фреймворк для решения типовых задач
Первичное развертывание проекта
npm init -y
npm i @scottwalker/node-framework
cp -r ./node_modules/@scottwalker/node-framework/demo/*.
node .Примеры базового использования фреймворка
const{ Application, Container }=require("@scottwalker/node-framework")constconfig=require("./config/main")constmodules=require("./modules")// Инициализировать контейнер зависимостейconstcontainer=newContainer()// Инициализировать приложениеconstapp=newApplication(container,modules,config)// Запустить приложениеapp.run()constpath=require("path")module.exports={router: {options: {jsonResponse: true},headers: {"Content-Type": "application/json"},handler: ({ response })=>response.ok("default"),errorHandler: ({ response })=>response.error("error"),},logger: {dir: path.resolve(__dirname,"../logs"),},server: {host: "localhost",port: 3030,ssl: {}}}Конфигурация имеет основные секции
router - Конфигурация роутера
options - опции маршрутов по умолчанию
jsonResponse - отдавать тело ответа в формате JSON
headers - HTTP заголовки ответа по умолчанию
handler - Обработчик успешных запросов к модулю по умолчанию
errorHandler - Обработчик неудачных запросов к модулю по умолчанию
logger - Конфигурация логгера
dir - Директория для логов
dateFormat - Обработчик формата даты в логах
server - Конфигурация сервера
host - Хост сервера
port - Порт сервера
ssl - Настройки SSL соединения
const{ Module }=require("@scottwalker/node-framework")module.exports=[newModule("base",{// Маршруты модуляroutes: [{method: "GET",path: "/",handler: ({ response })=>response.ok("Hello World!"),errorHandler: ({ response })=>response.error("Goodbye World!"),},],// Команды модуляcommands: [{name: "base/hello",params: [{key: "name",type: "string",required: true},{key: "p",alias: "price",type: "number",default: 100},],flags: [{key: "a",alias: "all"}],handler: ({ params })=>{const{ name, price, all }=paramsconsole.log({ name, price, all })}}],// Зависимости модуляdependencies: {"base/models/User": ({ name })=>newrequire("./models/User")(name)}})]Каждый модуль обязательно должен иметь свойства
routes - Описание маршрутизации модуля
dependencies - Описание зависимостей модуля
В версии 2.0.1 значительно переделана структура фреймворка по причине использования контейнера зависимостей.
Контейнер зависимостей использует 2 стратегии получения внедренных зависимостей
invoke - Вызвать зависимость, которая при первом вызове создается по стратегии make, а при дальнейших invoke вызовах, используется инициализированный ранее экземпляр зависимости make - Создать новый экземпляр зависимости
const{ Container }=require("@scottwalker/node-framework")// Инициализировать контейнер зависимостейconstcontainer=newContainer({// Клиенты"app/clients/HttpClient": ({},{ host, strict })=>newrequire("./clients/HttpClient")(host,strict),"app/clients/MongoClient": ({},{ config })=>newrequire("./clients/MongoClient")(config),// Модели"app/models/CampaignModel": ()=>newrequire("./models/CampaignModel")(),// Репозитории"app/repositories/CampaignRepository": ({ invoke })=>{constCampaignRepository=require("./repositories/CampaignRepository")constmongoClient=invoke("app/clients/MongoClient")returnnewCampaignRepository(mongoClient)},// Сервисы"app/services/CampaignService": ({ invoke, make })=>{constCampaignService=require("./services/CampaignService")consthttpClient=invoke("app/clients/HttpClient",{host: "localhost",strict: true})constcampaignRepository=make("app/repositories/CampaignRepository")returnnewCampaignService(httpClient,campaignRepository,{logged: true})}})В версии 2.1.4 добавлен механизм для выполнения консольных команд приложения.
const{ Shell }=require("@scottwalker/node-framework")constconfig=require("./config/main")constmodules=require("./modules")constcontainer=require("./container")(config)// Инициализировать командную оболочкуconstshell=newShell(container,modules,config)// Парсить переданные аргументы const{ name, params }=shell.parse(process.argv)// Выполнить командуshell.exec(name,params)