vespa-framework
v0.0.69
Published
NodeJs minimalist framework
Downloads
1,740
Readme
Vespa Framework
Requirements
- node v24
- Think
Install
$ npm install vespa-framework
$ node node_modules/vespa-framework/install.js
$ node app.jsBuilds
[!IMPORTANT]
$ node --run buildno funciona
VespaJs soporta stylus como preprocessor.
Con el comando $ node --run build el sistema busca todos las hojas de estilo ubicados en client/styles. Cada archivo con el sufijo -src.styl generara un archivo nuevo en la carpeta public/css.
El comando build lo que harà es:
- Compilar el
css - Copiar el
javascripta la carpeta publica - Copiar
assetsa la carpeta publica
CSS
Tu proyecto cargarà dos archivos CSS en el front-end: /public/css/framework.css.min.css y /public/css/theme.min.css.
Para ver clases del framework css y utilidades lee la documentacion. [LINK]
[!ALERT] TODO Documentacion de CSS y clases helpers
/my-project
├── package.json
└── client
└── styles
├── main-src.styl
├── file-1.styl
├── file-2.styl
└── example.styl
Compiles to
/my-project
├── package.json
└── public
└── css
├── main.min.css
└── example.min.css
Di default, el sistema inyecta un reset.css. Para evitarlo, basta comentar la linea 1 del archivo main-src-.styl de esta manera
- @require './../../node_modules/vespa-framework/models/stylus-framework-src.styl';
@require 'file-1.styl'
@require 'file-2.styl'
body
font-size 4remAl modificar (y guardar) un archivo stylus en la carpeta client, el sistema compilarà automaticamente. Para modificar la hoja de estilos de tu proyecto
Para mantener el codigo limpio, y estructurar las hojas de estilo de manera modular se puede agregar un nuevo archivo (sin el sufijo -src) e incluirlo como parte del archivo main-src.styl de esta manera
@require './../../node_modules/vespa-framework/models/stylus-framework-src.styl';
@require 'file-1.styl'
@require 'file-2.styl'
+@require 'file-3.styl'
body
font-size 4rem![IMPORTANT] Documentar como hacer para escribir CSS sin usar un preprocessor
Funcionalidades
Los archivos Stylus que se compilan tienen que incluir en el nombre `-src.styl`import {Db} from 'vespa-framework';
Se puede saber el nombre del Database llamando a Db.dbNameSe puede saber las estadisticas del database haciendo
import {Db} from 'vespa-framework';
Db.getStats().then( (stats) => {
console.log(stats);
});Crud
Es posible utilizar metodos de crud ya escritos
// 1. Crear una clase que extiende de -Crud-
import {Crud} from 'vespa-framework';
class Test extends Crud {
static collectionName = 'test';
}Tests
Test.bulkUpdate(docsUpdate);// En la clase se puede tener acceso a los metodos:
Test.updateOne({foo: 'bar'}).then( (result) => {
console.log(result);
})
Test.getById('66375e986361482741d1c230').then( (doc) => {
console.log(doc);
});
Test.findOne({foo: 'bar'}).then( (doc) => {
console.log(doc);
});
Test.getByQuery({foo: 'bar'}).then( (result) => {
console.log(result);
});
Test.count().then( (result) => {
console.log(result);
});
Test.deleteById('66375e986361482741d1c230').then( (result) => {
console.log(result);
});
const docs = [
{ name: "cake", healthy: false },
{ name: "lettuce", healthy: true },
{ name: "donut", healthy: false }
];
// Prevent additional documents from being inserted if one fails
const options = { ordered: true };
Test.insertMany(docs, options).then( (result) => {
console.log(result);
});Log management
Basic usage. More documentation on Pino library.
By default VespaJs logs into /logger.log (equivalent to set LOGGER_TARGET=file).
import {Logger} from 'vespa-framework';
Logger.info('Log an info msg');
Logger.warn('Log an warn msg');
Logger.error('Log an error msg');
Logger.debug('Log an debug msg');
Logger.trace('Log an trace msg');You cant set a different target by setting the environment variable.
LOGGER_TARGET=datadog
LOGGER_TARGET=console
LOGGER_TARGET=fileTodo management
Write as a comment in your javascript, HTML or css files a comment stating in @todo: to catch the message.
System will output the todo list in the terminal on startup
[!NOTE] It only works in development mode
Test runner
$ npm --testIcons
Use the route /icons/bootstrap.svg in your template to use an icon. All available icons in Bootstrap Icons
// Usage
app.get('/', (req, res) => {
res.send('<h1>Hello World!<img src="/icons/bootstrap.svg" alt="Bootstrap" width="32" height="32"></h1>');
});Global variables
- global.BASE_PATH: ./
- global.CLIENT_PATH: ./client
- global.SERVER_PATH: ./server
- global.VIEWS_PATH: ./client/views
- global.PUBLIC_PATH: ./public
SQLite support
Setear la variable de entorno SQL_DATABASE_PATH
| Variable | Example | Default | |---|---|---| | SQL_DATABASE_PATH | [absolute-path]/database.db | global.BASE_PATH |
[Note] La variable es opcional. Por defecto la base de datos se almacena
global.BASE_PATH/database.db
![IMPORTANT] Para usar la funcion node:sqlite la variable
useSQLiteen el archivovespa-config.jsontiene que estar seteada entrue
Usage
import {SQLite} from 'vespa-framework';
SQLite.exec();import VespaJs from 'vespa-framework';
VespaJs.SQLite.exec();Compatibility with technical-debt-cli
https://github.com/pieroblunda/technical-debt-cli
Tracing
--trace-deprecations --trace-warnings
$ node --run start package.jsonCode coverage
$ node --run coverage Run scripts
$ node --run helpAvailable scripts will be shown in terminal
Default routes
| Package | Description | |---|---| | /releases-notes | Render il contenuto del file releases-note.md senza formattazione | | /health | Render a health page |
NOTE: El usuario podria por motivos de SEO queres desactivar esta funcionalidad
External libraries
| Package | Description | |---|---| | body-parser | Node.js body parsing middleware. | | Chokidar | Watch stylus files to compile on change | | Colors | Color terminal stdout | | Compression | Node.js compression middleware | | Cors| Node.js cors middleware | | Express | Fast, unopinionated, minimalist Node.js web framework | | Helmet | Set header for security reasons | | MongoDb | The official MongoDB driver for Node.js. Used only in MondoDb Projects | | Pug | HTML preprocessor | | Stylus | CSS preprocessor. Used only in stylus projects | | Technical Debt cli | Read debt from te terminal |
Contribuiting guidelines
Internationalization (i18n)
Los archivos se traducen en JSON usando los archivos ubicados en la carpeta locales, por ejemplo locales/es-ES.json.
** How to use **
En el Preprocessor de HTML, por ahora solo Pug, usar la variable Locale de esta manera:
h1 #{Locale.e9595907}{
"e9595907": "Escalabilidad como servicio para web agencies"
}Order de prioridades
- URL (maxima prioridad)
- Cookie de opcion de usuario
- Lengua del navegador
- Lengua por defecto del vespa-framework
Nota: Configurar idiomas en el archivo de configuracion podria ahorrar una cookie y algo de performance.
Cookies
| CookieName | Type | Description | |---|---|---| | locale | Functionality | It is used to store the user's code language used to L10n |
Middlewares
| Metodo | Description | |---|---| | parseUrl | parsea el URL |
Todos los middlewares se usan importando el modelo middleware Middleware y usando el metodo
Tree directory
Luego de instalar VespaJs la estructura de tu repositorio se verà de esta manera:
/my-project
├── client
| ├── icons
| ├── js
| ├── media
| ├── styles
| └── views
├── coverage
├── fixtures
├── locale
├── node_modules
├── public
| ├── css
| ├── js
| └── media
├── reports
├── scripts
├── server
| ├── controllers
| ├── middlewares
| └── models
├── test
├── .env
├── .gitignore
├── app.js
├── package-lock.json
├── package.json
├── readme.md
├── todo.md
└── vespa-config.jsonPara agregar un archivo de javascript (NodeJs) puedes agregar un archivo en las carpetas /client/js (para javascript), /client/styles (para Stylus y css), /client/views (para archivos pug) y /client/media (para assets). Es bastante intuitivo.
Para agregar un archivo de javascript (NodeJs) puedes agregar un archivo en las carpetas /server/controllers, /server/middlewares y /server/models. Es bastante intuitivo.
Para agregar una nueva ruta, existe un modelo que se llama MyRoutes en el archivo /server/models/routes.server.model.js.
Framework
Los modulos del framework son:
| Modulo | Descripcion | | --- | --- | | Core | Reservado del sistema | | StylusVespa | Funcionalidades para compilar Stylus | | Server | Reservado del sistema | | Routes | Reservado del sistema | | Db | Database MongoDB | | Crud | Crud de MongoDb | | Utils | Utilidades de backend | | Environment | Utilidades de ambiente | | SQLite | Database SQlite | | Locale | Clase para la localizacion | | Logger | Clase para funciones de logging | | localeMiddleware | Middleware para la i18n |
import VespaJs from 'vespa-framework'
console.log(VespaJs.utils.getAppVersion())import {Utils} from 'vespa-framework'
console.log(Utils.getAppVersion())Archivo de configuracion VespaJs
{
"useSQLite": true
}| Modulo | Descripcion |
| --- | --- |
| useSQLite | Si esta es true, el sistema lanzararà la conexion a SQlite. Activalo cuando quieras que tu proyecto use una BBDD SQLite. Default: true |
Actualizar VespaJs
$ npm update vespa-frameworkSupport for wrangler configuration
https://developers.cloudflare.com/workers/wrangler/configuration/
