Repository: LeCoupa/awesome-cheatsheets
Branch: master
Commit: 64d33cf36db7
Files: 57
Total size: 729.8 KB
Directory structure:
gitextract_9vlyh4xo/
├── .gitignore
├── .husky/
│ └── commit-msg
├── LICENSE
├── README.md
├── _design/
│ ├── Awesome Cheatsheets.sketch
│ └── awesome_cheatsheets_logo.psd
├── backend/
│ ├── adonis.js
│ ├── django.py
│ ├── express.js
│ ├── feathers.js
│ ├── laravel.php
│ ├── moleculer.js
│ ├── node.js
│ └── sails.js
├── commitlint.config.js
├── databases/
│ ├── mongodb.sh
│ ├── mysql.sh
│ └── redis.sh
├── frontend/
│ ├── angular.js
│ ├── angularjs.js
│ ├── css3.css
│ ├── ember.js
│ ├── html5.html
│ ├── react.js
│ ├── tailwind.css
│ └── vue.js
├── languages/
│ ├── C#.txt
│ ├── C.txt
│ ├── XML.md
│ ├── bash.sh
│ ├── golang.md
│ ├── java.md
│ ├── javascript.js
│ ├── php.php
│ └── python.md
└── tools/
├── aws.sh
├── curl.sh
├── docker.sh
├── drush.sh
├── elasticsearch.js
├── emmet.md
├── firebase_cli.md
├── gcp.md
├── git.sh
├── heroku.sh
├── kubernetes.md
├── macos.sh
├── nanobox_boxfile.yml
├── nanobox_cli.sh
├── nginx.sh
├── pm2.sh
├── puppeteer.js
├── sublime_text.md
├── ubuntu.sh
├── vim.txt
├── vscode.md
└── xcode.txt
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Miscelleaneous
.DS_Store
# Editors
.vscode/
# Vim
*.swp
================================================
FILE: .husky/commit-msg
================================================
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no -- commitlint --edit ""
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2018 Julien Le Coupanec
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
[](https://lecoupa.github.io/awesome-cheatsheets/)
[](https://awesome.re) [](https://github.com/LeCoupa/awesome-cheatsheets/blob/master/LICENSE)
**WEBSITE DIRECTORY**: [Available here](https://lecoupa.github.io/awesome-cheatsheets/).
> 📚 Awesome cheatsheets for popular programming languages, frameworks and development tools. They include everything you should know in one single file.
## 🤔 Why Awesome-Cheatsheets?
I usually make a cheat sheet when I want to improve my skills in a programming language, a framework or a development tool. [I started doing these kinds of things a long time ago on Gist](https://gist.github.com/LeCoupa). To better keep track of the history and to let people contribute, I re-organized all of them into this single repository. Most of the content is coming from official documentation and some books I have read.
Feel free to take a look. You might learn new things. They have been designed to provide a quick way to assess your knowledge and to save you time.
## 📚 Table of Contents
### 📃 Languages
View cheatsheets
#### Command line interface
- [Bash](languages/bash.sh)
#### Imperative
- [C](languages/C.txt)
- [C#](languages/C%23.txt)
- [Go](languages/golang.md)
- [Java](languages/java.md)
- [PHP](languages/php.php)
- [Python](languages/python.md)
#### Functional
- [JavaScript](languages/javascript.js)
### 📦 Backend
View cheatsheets
#### PHP
- [Laravel](backend/laravel.php)
#### Python
- [Django](backend/django.py)
#### Javascript
- [Adonis.js](backend/adonis.js)
- [Express.js](backend/express.js)
- [Feathers.js](backend/feathers.js)
- [Moleculer](backend/moleculer.js)
- [Node.js](backend/node.js)
- [Sails.js](backend/sails.js)
### 🌐 Frontend
View cheatsheets
#### Basics
- [HTML5](frontend/html5.html)
- [CSS3](frontend/css3.css)
#### Frameworks
- [React.js](frontend/react.js)
- [Vue.js](frontend/vue.js)
- [Tailwind.css](frontend/tailwind.css)
- [Ember.js](frontend/ember.js)
- [Angular (2+)](frontend/angular.js)
- [AngularJS](frontend/angularjs.js)
### 🗃️ Databases
View cheatsheets
#### SQL
- [MySQL](databases/mysql.sh)
#### NoSQL
- [Redis](databases/redis.sh)
### 🔧 Tools
View cheatsheets
#### Development
- [cURL](tools/curl.sh)
- [Drush](tools/drush.sh)
- [Elasticsearch](tools/elasticsearch.js)
- [Emmet](tools/emmet.md)
- [Git](tools/git.sh)
- [Puppeteer](tools/puppeteer.js)
- [Sublime Text](tools/sublime_text.md)
- [VIM](tools/vim.txt)
- [Visual Studio Code](tools/vscode.md)
- [Xcode](tools/xcode.txt)
#### Infrastructure
- [AWS CLI](tools/aws.sh)
- [Docker](tools/docker.sh)
- [Heroku CLI](tools/heroku.sh)
- [Kubernetes](tools/kubernetes.md)
- [Nanobox Boxfile](tools/nanobox_boxfile.yml)
- [Nanobox CLI](tools/nanobox_cli.sh)
- [Nginx](tools/nginx.sh)
- [PM2](tools/pm2.sh)
- [Ubuntu](tools/ubuntu.sh)
- [Firebase CLI](tools/firebase_cli.md)
## 🙌🏼 How to Contribute?
You are more than welcome to contribute and build your own cheat sheet for your favorite programming language, framework or development tool. Just submit changes via pull request and I will review them before merging.
## 👩💻👨💻 Our valuable Contributors
================================================
FILE: backend/adonis.js
================================================
/********************************************************************************************
* ADONIS CHEATSHEET
* https://adonisjs.com/
********************************************************************************************/
/********************************************************************************************
* AVAILABLE CLI COMMANDS
* https://adonisjs.com/docs/ace
********************************************************************************************/
build // Compile typescript code to Javascript. Optionally watch for file changes.
invoke // Invoke post install instructions on a given AdonisJs package.
serve // Compile typescript code to Javascript and start the HTTP server.
// Dump
dump:rcfile // Dump contents of .adonisrc.json file along with defaults.
// Generate
generate:key // Generate a new APP_KEY secret.
generate:manifest // Generate manifest file to execute ace commands.
// List
list:routes // List application routes.
// Make
make:command // Make a new ace command.
make:controller // Make a new HTTP controller.
make:middleware // Make a new middleware.
make:migration // Make a new migration.
make:provider // Make a new IoC container provider.
make:validator // Make a new validator.
make:view // Make a new view template.
// Migrations
migration:run // Run all pending migrations.
migration:rollback // Rollback last set of migrations.
migration:refresh // Rollback all migrations to the 0 batch then re-run them from the start.
migration:reset // Rollback all migrations to the 0 batch.
migration:status // Get the status of all the migrations.
/********************************************************************************************
* REQUEST
* https://adonisjs.com/docs/request
********************************************************************************************/
request.all() // Returns an object containing all request data (merges query params and request body data).
request.get() // Returns an object containing query params data.
request.post() // Returns an object containing request body data.
request.raw() // Returns raw body data as a string.
request.only(['username', 'age']) // Returns an object with only the specified keys.
request.collect(['username', 'age']) // Formats so it’s ready to save to the database.
request.except(['csrf_token', 'submit']) // Returns an object with everything except the specified keys (opposite of only).
request.input('drink', 'coffee') // Get the value of a given key (if it doesn’t exist, return the default value).
request.headers() // Returns an object of all header data.
request.header('some-other-header', 'default') // The header value for a given key (optionally with default value).
request.cookies() // Returns an object of all cookie data.
request.cookie('cart_total', 0) // Returns the cookie value for a given key (optionally with default value).
request.plainCookies() // Returns an object of all raw cookie data.
request.plainCookie('cart_total', 0) // Returns the raw cookie value for a given key (optionally with default value).
request.accepts(['json', 'html']) // Reads the Accept header to help determine the response format.
request.language(['en', 'fr']) // Language can also be negotiated based upon the Accept-Language header.
request.url() // Returns the current request url.
request.originalUrl() // Returns the full current request url with query strings.
request.method() // Returns the HTTP request method.
request.intended() // Returns the intended request HTTP method.
request.ip() // Returns the most trusted ip address for the user.
request.ips() // Returns an array of ips from most to the least trusted (removes the default ip address, which can be accessed via the ip method).
request.subdomains() // Returns a list of request subdomains (removes www from the list).
request.ajax() // Checks for X-Requested-With header to determine if the request is ajax or not.
request.pjax() // This methods looks for the X-PJAX header to identify if a request is pjax or not.
request.hostname() // Returns the request hostname.
request.protocol() // Return the request protocol.
request.match(['posts/:id']) // Returns whether the passed set of expressions match the current request URL.
request.hasBody() // A boolean indicating if the request has a post body (mainly used by the BodyParser to determine whether or not to parse the body).
request.is(['json', 'html']) // The is method returns the best matching content type for the current request. The check is entirely based upon the content-type header.
/********************************************************************************************
* RESPONSE
* https://adonisjs.com/docs/response
********************************************************************************************/
response.header("Content-type", "application/json"); // Set a header value.
response.safeHeader("Content-type", "application/json"); // Only set a header value if it does not already exist.
response.removeHeader("Content-type"); // Remove an existing header.
response.type("application/json"); // Set the Content-Type header.
response.cookie("cartTotal", 20); // Set a cookie value.
response.clearCookie("cartTotal"); // Remove an existing cookie value (by setting its expiry in the past).
response.plainCookie("cartTotal", 20); // Set a plain cookie.
response.redirect(url, [(sendParams = false)], [(status = 302)]); // Redirect request to a different url (by default it will set the status as 302).
response.route(route, [data], [domain], [(sendParams = false)], [(status = 302)]); // Redirect to a route (via route name or controller method).
response.download(filePath); // Stream the file to the client.
response.attachment(filePath, [name], [disposition]); // Force download the file.
response.continue(); // 100 status code
response.switchingProtocols(); // 101 status code
response.ok(); // 200 status code
response.created(); // 201 status code
response.accepted(); // 202 status code
response.nonAuthoritativeInformation(); // 203 status code
response.noContent(); // 204 status code
response.resetContent(); // 205 status code
response.partialContent(); // 206 status code
response.multipleChoices(); // 300 status code
response.movedPermanently(); // 301 status code
response.found(); // 302 status code
response.seeOther(); // 303 status code
response.notModified(); // 304 status code
response.useProxy(); // 305 status code
response.temporaryRedirect(); // 307 status code
response.badRequest(); // 400 status code
response.unauthorized(); // 401 status code
response.paymentRequired(); // 402 status code
response.forbidden(); // 403 status code
response.notFound(); // 404 status code
response.methodNotAllowed(); // 405 status code
response.notAcceptable(); // 406 status code
response.proxyAuthenticationRequired(); // 407 status code
response.requestTimeout(); // 408 status code
response.conflict(); // 409 status code
response.gone(); // 410 status code
response.lengthRequired(); // 411 status code
response.preconditionFailed(); // 412 status code
response.requestEntityTooLarge(); // 413 status code
response.requestUriTooLong(); // 414 status code
response.unsupportedMediaType(); // 415 status code
response.requestedRangeNotSatisfiable(); // 416 status code
response.expectationFailed(); // 417 status code
response.unprocessableEntity(); // 422 status code
response.tooManyRequests(); // 429 status code
response.internalServerError(); // 500 status code
response.notImplemented(); // 501 status code
response.badGateway(); // 502 status code
response.serviceUnavailable(); // 503 status code
response.gatewayTimeout(); // 504 status code
response.httpVersionNotSupported(); // 505 status code
/********************************************************************************************
* ROUTING
* https://adonisjs.com/docs/routing
********************************************************************************************/
Route.get(url, closure) // Register route for GET verb.
Route.post(url, closure) // Register route for POST verb.
Route.put(url, closure) // Register route for PUT verb.
Route.patch(url, closure) // Register route for PATCH verb.
Route.delete(url, closure) // Register route for DELETED verb.
Route.any(url, closure) // Register route for all HTTP verbs.
Route.on('/').render('welcome') // Render a view directly.
Route.route('/', () => {}, ['GET', 'POST', 'PUT']) // Register route for multiple verbs.
Route.get('users', closure).as('users.index') // Assign a unique name to the route.
Route.get('users', closure).formats(['json', 'html'], true) // Force client to define the route format.
Route.resource('users', 'UserController') // Define a resource route for CRUD operations.
Route.resource('users', 'UserController').apiOnly() // Remove create and edit routes.
Route.resource('users', 'UserController').only(['index']) // Keeps only the passed routes.
Route.resource('users', 'UserController').except(['index']) //Keeps all routes except the passed routes.
Route.group(() => {}) // Define a group of routes.
Route.group(() => {}).middleware(['auth']) // Attach a middleware.
Route.group(() => {}).formats(['json']) // Define response formats.
Route.group(() => {}).prefix('api/v1') // Define a prefix for a group of routes.
Route.group(() => {}).namespace('Admin') // Prefix the namespace of the bound controller.
Route.group(() => {}).domain('blog.sthg.com') // Specify which domain goup routes belong to.
/********************************************************************************************
* VALIDATOR
* https://indicative-v5.adonisjs.com/
********************************************************************************************/
const indicative = require("indicative");
const rules = {
email: "required|email|unique:users",
password: "required|min:6|max:30",
};
// Indivative methods
indicative.validate(data, rules); // Validate data with defined rules.
indicative.validateAll(data, rules); // Same as validate but continues to validate all fields, whereas the validate method stops on first error.
indicative.is.email(emailAddress); // Raw validator.
indicative.extend("exists", existsFn); // Add your own rules.
indicative.sanitize(data, rules); // Returns a new object with sanitized data:.
indicative.sanitizor.normalizeEmail(emailAddress); // Raw sanitizor.
// Validations
above // Makes sure the value provided by the end user is above the expected value.
accepted // Ensures that the field under validation is accepted.
after // Ensures the value of the field is after the expected date.
afterOffsetOf // Ensures the date is after a given offset of a given time period.
alpha // Makes sure the field under validation is alpha only.
alphaNumeric // Makes sure the field under validation is alpha numeric only.
array // Ensure the value is a valid array. Also this validation will never validate the size of array.
before // Ensures the value of field under validation is before a given date.
beforeOffsetOf // Ensures the date is before a given offset of a given time period.
boolean // Ensures the value of a field is a boolean.
confirmed // Ensures a field value as confirmed using a _confirmation convention. This is mainly used for password confirmation field.
date // Ensures the field under validation is a valid date. The value can be a date object or a valid date string.
dateFormat // Ensures the date or date time is valid as the one of the defined formats.
different // Ensures the value of the field under validation is always different from the targeted field value.
email // Ensures the field under validation is a valid email format.
endsWith // Ensure the value of field under validation ends with a certain substr. This validation will also trim whitespaces before making the check.
equals // Ensures 2 values are lossely same. This validation will not check for the same type, but instead checks for the same value.
in // Ensures the value of a given field matches one of expected values.
includes // Ensures the value of field under validation contains a given substring.
integer // Ensures the value is a valid integer. Also string representation of a number will return true.
ip // Ensures the value is a valid ip address as per ipv4 and ipv6 specs.
ipv4 // Ensures the value is a valid ip address as per ipv4 spec only.
ipv6 // Ensures the value is a valid ip address as per ipv6 spec only.
json // Ensures the value of field under validation is safe to be parsed using JSON.parse method.
max // Ensures the length of a string or array is not greater than the defined length.
min // Ensures the length of a string or array is not is not less than the expected length
notEquals // Makes sure that the value of field under validation is not same as the defined value.
notIn // Makes sure that the value of field under validation is not from one of the defined values.
number // Makes sure that the value of field under validation is a valid number. The validation will pass for floats too, since it uses typeof internally.
object // Ensures the value of field under validation is a valid Javascript object. The validation will fail for Arrays, though they are objects too in Javascript.
range // Ensures the value of field under validation is under a given range. The values will be cased to Number automatically.
regex // Ensures the value of field under validation, passes the regex test. The regex can be defined as a string or a RegExp object.
required // Ensures the value of field under validation is not empty (i.e. not an empty object, empty array, empty string, null or undefined).
requiredIf // The field is checked for required validation, when expected field exists.
requiredWhen // The field is checked for required validation, when expected field value is same as the expected value.
requiredWithAll // Ensures the field is required when all other fields have non-empty values.
requiredWithAny // Ensures the field is required when any of the other fields have non-empty values.
requiredWithoutAll // Ensures the field is required when all of the other fields has empty values.
requiredWithoutAny // Ensures the field is required when any of the other fields has empty values.
same // Ensures the value of 2 fields are same.
startsWith // Ensure the value of field under validation starts with a certain substr. This validation will also trim whitespaces before making the check.
string // Ensures the value is a string.
under // Ensures the value of a field is under a certain value. All values will be casted to Number.
url // Ensures the value is a valid URL format.
/********************************************************************************************
* LUCID
* https://adonisjs.com/docs/lucid
********************************************************************************************/
Model.find() // Find a record using the primary key (always returns one record).
Model.findOrFail() // Similar to find, but instead throws a ModelNotFoundException when unable to find a record.
Model.findBy() // Find a record using a key/value pair (returns the first matching record).
Model.findByOrFail() // Similar to findBy, but instead throws a ModelNotFoundException when unable to find a record.
Model.first() // Find the first row from the database.
Model.firstOrFail() // Similar to first, but instead throws a ModelNotFoundException when unable to find a record.
Model.last() // Find the latest row from the database.
Model.findOrCreate(whereAttributes, values) // Find a record, if not found a new record will be created and returned.
Model.pick(rows = 1) // Pick x number of rows from the database table (defaults to 1 row).
Model.pickInverse(rows = 1) // Pick x number of rows from the database table from last (defaults to 1 row).
Model.ids() // Return an array of primary keys.
Model.pair(lhs, rhs) // Returns an object of key/value pairs (lhs is the key, rhs is the value).
Model.all() // Select all rows.
Model.truncate() // Delete all rows (truncate table).
Model.getCount() // Return a count of records in a given result set.
Model.create(jsonAttributes) // Return model instance after saving it into the database.
Model.createMany(arrayAttributes) // Return an array of model instances after saving them into the database.
Model.toJSON() // Converts a serializable instance to a plain array/object.
Model.query().setHidden(['password']) // Define hidden fields.
Model.query().setVisible(['title', 'body']) // Define visible fields.
Model.query().paginate() // Returns an object with metadata and data property that has a list of model results.
instance.fill(jsonAttributes) // Remove all existing values, only set the specified attributes.
instance.merge(jsonAttributes) // Modifies the specified attributes.
instance.save() // Save the instance to the database.
instance.delete() // Delete model instance from the database.
instance.associate(id) // Exclusive to belongsTo relationship, where it associates two model instances together.
instance.dissociate(id) // The opposite of associate, where you just drop the relationship
instance.attach(arrayOfIds, callback) // Works with the belongsToMany relationship to attach a relationship inside the pivot table. The attach method accepts an optional callback receiving the pivotModel instance, allowing you to set extra properties on a pivot table if required:
instance.detach(arrayOfIds) // The opposite of the attach method, and it removes the relationship from the pivot table only.
/********************************************************************************************
* QUERY BUILDER
* https://adonisjs.com/docs/query-builder
* http://knexjs.org/
********************************************************************************************/
const Database = use('Database')
// Available where clauses
where(~mixed~)
orWhere(~mixed~)
whereNot(~mixed~)
orWhereNot(~mixed~)
whereIn(column|columns, array|callback|builder)
orWhereIn(column | columns, array | callback | builder)
whereNotIn(column, array|callback|builder)
orWhereNotIn(column, array | callback | builder)
whereNull(column)
orWhereNull(column)
whereNotNull(column)
orWhereNotNull(column)
whereExists(builder | callback)
orWhereExists(builder | callback)
whereNotExists(builder | callback)
orWhereNotExists(builder | callback)
whereBetween(column, range)
orWhereBetween(column, range)
whereNotBetween(column, range)
orWhereNotBetween(column, range)
whereRaw(query, [bindings])
/********************************************************************************************
* DATABASE HOOKS
* https://adonisjs.com/docs/database-hooks
********************************************************************************************/
beforeCreate // Before creating a new record.
afterCreate // After a new record is created.
beforeUpdate // Before updating a record.
afterUpdate // After a record has been updated.
beforeSave // Before creating or updating a new record.
afterSave // After a new record has been created or updated.
beforeDelete // Before removing a record.
afterDelete // After a record is removed.
afterFind // After a single record is fetched from the database.
afterFetch // After the fetch method is executed.The hook method receives an array of model instances.
afterPaginate // After the paginate method is executed.The hook method receives two arguments: an array of model instances and the pagination metadata.
/********************************************************************************************
* EVENTS
* https://adonisjs.com/docs/events
********************************************************************************************/
Event.on(event, listener) // Bind single or multiple listeners for a given event. The listener can be a closure function or reference to one (or many) IoC container bindings.
Event.when(event, listener) // The when method aliases the on method.
Event.once(event, listener) // Same as on, but only called one time.
Event.onAny(listener) // Bind listener for any event
Event.times(number) // The times method is chained with on or when to limit the number of times the listener should be fired.
Event.emit(event, data) // Emit an event with optional data.
Event.fire(event, data) // The fire method aliases the emit method.
Event.removeListener(event, listener) // Remove listener(s) for a given event.
Event.off(event, listener) // The off method aliases the removeListener method.
Event.removeAllListeners(event) // Remove all listeners for a given event.
Event.listenersCount(event) // Return the number of listeners for a given event.
Event.getListeners(event) // Return an array of listeners for a given event.
Event.hasListeners(event) // Return a boolean indicating whether there are any listeners for a given event.
/********************************************************************************************
* LOGGER
* https://adonisjs.com/docs/sessions
********************************************************************************************/
const Logger = use('Logger')
Logger.level = 'debug' // Sed default config level
Logger.emerg(msg[, …data]) // Print an emergency log (level 0).
Logger.alert(msg[, …data]) // Print an alert log (level 1).
Logger.crit(msg[, …data]) // Print a critical log (level 2).
Logger.error(msg[, …data]) // Print an error log (level 3).
Logger.warning(msg[, …data]) // Print a warning log (level 4).
Logger.notice(msg[, …data]) // Print a notice log (level 5).
Logger.info(msg[, …data]) // Print an info log (level 6).
Logger.debug(msg[, …data]) // Print a debug log (level 7).
Logger.transport(transport) // Switch transport on the fly.
/********************************************************************************************
* ENCRYPTION AND HASHING
* https://adonisjs.com/docs/encryption-and-hashing
********************************************************************************************/
const Encryption = use('Encryption')
Encryption.encrypt(string) // Encrypt a given value.
Encryption.decrypt(string) // Decrypt an encrypted value.
const Hash = use('Hash')
await Hash.make(string[, config]) // Hash a plain string value.
await Hash.verify(string, hashedString) // Since you cannot decrypt a hash, you can verify the user input against the previously hashed value.
/********************************************************************************************
* SESSIONS
* https://adonisjs.com/docs/sessions
********************************************************************************************/
session.put(key, value); // Add a key/value pair to the session store.
session.get(key, [defaultValue]); // Return the value for a given key (accepts an optional default value).
session.all(); // Get everything back as an object from the session store.
session.increment(key, [steps]); // Increment the value for a given key (ensure the previous value is a number).
session.decrement(key, [steps]); // Decrement the value for a given key (ensure the previous value is a number).
session.forget(key); // Remove a key/value pair from the session store.
session.pull(key, [defaultValue]); // Return (and then remove) a key/value pair from the session store.
session.clear(); // Empty the session store.
session.flashAll() // Flash the request form data.
session.flashOnly() // Flash only the selected fields.
session.flashExcept() // Flash the request form data except the selected fields.
session.withErrors() // Flash with an array of errors.
session.flash() // Flash a custom object.
/********************************************************************************************
* FILE STORAGE
* https://adonisjs.com/docs/file-system
********************************************************************************************/
const Drive = use('Drive')
Drive.exists(relativePath) // Find if a file/directory exists or not.
Drive.get(relativePath, encoding = utf-8) // Get file contents as a buffer or string.
Drive.getStream(relativePath) // Get file as a stream.
Drive.put(relativePath, content, options = {}) // Create a new file with given contents (creates any missing directories).
Drive.prepend(relativePath, content, options = {}) // Prepend content to a file (creates a new file if path doesn’t exist).
Drive.append(relativePath, content, options = {}) // Append content to a file (creates a new file if path doesn’t exist).
Drive.delete(relativePath) // Remove existing file.
Drive.move(src, dest, options = {}) // Move file from one directory to another.
Drive.copy(src, dest, options = {}) // Copy file from one directory to another.
// For S3 & Spaces drivers
Drive.getObject(location, params) // Get S3 object for a given file (for params info, see S3 params).
Drive.getUrl(location, [bucket]) // Get url for a given file (accepts optional alternative bucket param).
Drive.getSignedUrl(location, expiry = 900, params) // Get signed url for a given file (expiry set to 15mins by default).
/********************************************************************************************
* HELPERS
* https://adonisjs.com/docs/helpers
********************************************************************************************/
const Helpers = use('Helpers')
Helpers.appRoot() // Returns path to the application root.
Helpers.publicPath([toFile]) // Returns path to the public directory or file inside the directory.
Helpers.configPath([toFile]) // Returns path to the config directory or file inside the directory.
Helpers.resourcesPath([toFile]) // Returns path to the resources directory or file inside the directory.
Helpers.migrationsPath([toFile]) // Returns path to the migrations directory or file inside the directory.
Helpers.seedsPath([toFile]) // Returns path to the seeds directory or file inside the directory.
Helpers.databasePath([toFile]) // Returns path to the database directory or file inside the directory.
Helpers.viewsPath([toFile]) // Returns path to the views directory or file inside the directory.
Helpers.tmpPath([toFile]) // Returns path to the tmp directory or file inside the directory.
Helpers.promisify() // Returns promisified callback functions.
Helpers.isAceCommand() // Returns whether the process was started as the ace command or not.
/********************************************************************************************
* SOCIAL AUTHENTICATION
* https://adonisjs.com/docs/social-auth
********************************************************************************************/
// Drivers: Facebook, Github, Google, Instagram, Linkedin, Twitter, Foursquare.
ally.redirect() // Redirect user to the 3rd party website.
ally.getRedirectUrl() // Get redirect URL back as a string.
ally.scope(scopesArray) // Define runtime scopes before redirecting the user.
ally.fields(fieldsArray) // Fields to be fetched when getting the authenticated user profile.
ally.getUser() // Get the user profile of an authenticated user (returns an AllyUser instance).
ally.getUserByToken(accessToken, [accessSecret]) // Returns the user details using the accessToken.
user.getId() // Returns the user id.
user.getName() // Returns the user name.
user.getEmail() // Returns the user email.
user.getNickname() // Returns the nickname / display name of the user.
user.getAvatar() // Returns public URL to the user’s profile picture.
user.getAccessToken() // Returns the access token which may be used later to update the user profile.
user.getRefreshToken() // Refresh token to be used when access token expires.
user.getExpires() // Access token expiry data.
user.getTokenSecret() // Returns token secret.
user.getOriginal() // Original payload returned by the 3rd party provider.
================================================
FILE: backend/django.py
================================================
# *****************************************************************************
# CODING STYLE > MAKING YOUR CODE READABLE
# *****************************************************************************
# 1. Avoid abbreviating variable names.
# 2. Write out your function argument names.
# 3. Document your classes and methods.
# 4. Comment your code.
# 5. Refactor repeated lines of code into reusable functions or methods.
# 6. Keep functions and methods short. A good rule of thumb is that scrolling
# should not be necessary to read an entire function or method.
# TIP: Use Flake8 for Checking Code Quality.
# *****************************************************************************
# CODING STYLE > THE WORD ON IMPORTS
# *****************************************************************************
# Imports should be grouped in the following order:
# 1. Standard library imports.
# 2. Core Django imports.
# 3. Third-party app imports.
# 4. Imports from your apps.
# Use explicit relative imports.
# Avoid using import *
# *****************************************************************************
# CODING STYLE > OTHERS
# *****************************************************************************
# Use underscores in URL pattern names rather than dashes.
# *****************************************************************************
# CODING STYLE > DATABASE
# *****************************************************************************
# 1.Register your app in admin file in your app folder to use admin panel in django
# 2.Create a superuser using command python manage.py createsuperuser
# 3.Remember to migrate after you change anything in your models.py file
# 4.Use /admin/ page to add data in your tables for testing purpose
# *****************************************************************************
# Deployment
# *****************************************************************************
# add your media, database, venv, __pycache__ to the .gitignore (there is a compelete list that you can find here: https://github.com/jpadilla/django-project-template/blob/master/.gitignore)
# keep migration files in the git (you will need to migrate them in target server)
# don't run "makemigrations" in the target server (you will need to just run "migrate")
# $ pip freeze > requirements.txt
# make appropriate changes in your project settings.py file (change DEBUG to False and etc)
# push your code to your git-server
# pull your code in your target server
# give right permissions to the web-server (e.g. $ chown www-data:www-data -R /var/www/myproject)
# make a new venv in the target server and activate it
# $ sudo pip install -r requirements.txt
# sudo ./venv/bin/python3 manage.py migrate
# restart your web-server (in case of apache: $ sudo service apache2 restart)
# *****************************************************************************
# DJANGO-ADMIN
# *****************************************************************************
django-admin check # Checks the entire django project for potential problems
django-admin changepassword # Allows changing a user’s password. It prompts you to enter a new password twice for the given user.
django-admin clearsessions # Can be run as a cron job or directly to clean out expired sessions.
django-admin collectstatic # Helps to collect all the static files in the one mentioned directory
django-admin createsuperuser # Creates a superuser account (a user who has all permissions).
django-admin compilemessages # Compiles .po files to .mo files for use with builtin gettext support
django-admin createcachetable # Creates the tables needed to use the SQL cache backend.
django-admin dbshell # Runs the command-line client for specified database, or the default database if none is provided.
django-admin diffsettings # Displays differences between the current settings.py and Django's default settings.
django-admin dumpdata # Output the contents of the database as a fixture of the given format (using each model's default manager unless --all is specified).
django-admin flush # Removes ALL DATA from the database, including data added during migrations. Does not achieve a "fresh install" state.
django-admin inspectdb # Introspects the database tables in the given database and outputs a Django model module.
django-admin loaddata # Installs the named fixture(s) in the database.
django-admin makemessages # Runs over the entire source tree of the current directory and pulls out all strings marked for translation. It creates (or updates) a message file in the conf/locale (in the django tree) or locale (for projects and applications) directory. You must run this command with one of either the --locale, --exclude, or --all options.
django-admin help # display usage information and a list of the commands provided by each application
django-admin makemigrations # create new migrations to the database based on the changes detected in the models
django-admin migrate # synchronize the database state with your current state project models and migrations
django-admin remove_stale_contenttypes # Deletes stale content types (from deleted models) in your database.y.
django-admin runserver # start the development webserver at 127.0.0.1 with the port default 8000
django-admin sendtestemail # Sends a test email to the email addresses specified as arguments.
django-admin shell # Runs a Python interactive interpreter. Tries to use IPython or bpython, if one of them is available. Any standard input is executed as code.
django-admin showmigrations # Shows all available migrations for the current project.
django-admin sqlflush # Returns a list of the SQL statements required to return all tables in the database to the state they were in just after they were installed.
django-admin sqlmigrate # Prints the SQL statements for the named migration.
django-admin sqlsequencereset # Prints the SQL statements for resetting sequences for the given app name(s).
django-admin squashmigrations # Squashes an existing set of migrations (from first until specified) into a single new one.
django-admin startapp # create a new django application with the specified name
django-admin startproject # create a new project directory structure
django-admin testserver # Runs a development server with data from the given fixture(s).
django-admin version # display the current django version
# *****************************************************************************
# Starting a django project in python3
# *****************************************************************************
# 1. $ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py; python3 get-pip.py
# 2. $ pip install virtualenv
# 3. $ mkdir django-projects
# 4. $ cd django-projects
# 5. $ virtualenv venv
# 6. $ source venv/bin/activate
# 7. $ pip install django
# 8. $ django-admin startproject myproject
# 9. $ django-admin startapp myapp
# 10. $ python manage.py runserver
================================================
FILE: backend/express.js
================================================
/* *******************************************************************************************
* API
* http://expressjs.com/en/api.html
* ******************************************************************************************* */
`npm i express --save` or`yarn add -D express``(-D saves it as a dev dependency)`
`yarn add -D @types/express``(Installing for TS)`
const express = require("express"); // Importing the express library.
const app = express(); // Intializing the imported express application
/* *******************************************************************************************
* GLOBAL OBJECTS
* http://expressjs.com/en/api.html#express.json
* ******************************************************************************************* */
```Methods```;
`express.json([options]);`
options: `
inflate // to manage the deflated bodies like enabling and disabling
limit // Controls the maximum request body size.
reviver // It is passed directly to JSON.parse as an second argument
type // This is used to determine the type of middleware will parse
verify // It is an undefined function which used to verify the middleware parsing.
`;
`express.raw([options]);`
options: `
inflate // to manage the deflated bodies like enabling and disabling
limit // Controls the maximum request body size.
type // This is used to determine the type of middleware will parse
verify // It is an undefined function which used to verify the middleware parsing.
`;
`express.Router([options]);`
options: `
caseSensitive //Enables case sensitivity
mergeParams //if param names of child and parent are conflicted then the child takes the precedence
strict // Enables Strict routing
`;
`express.static(root, [options]);`
options: `
dotfiles // determines how dotfiles are used
etag // Operates etag generation
extensions // Operates file extension fallback
fallthrough // Enable or disable the immutable directive in the Cache-Control response header
index // sends the specified directory index file
LastModified // sets the Last-Modified header to the last modified date
setHeaders // Function for setting HTTP headers to serve with the file
`;
`express.text([options]);`
options: `
defaultCharset // Sets the default charset for the text context.
inflate // to manage the deflated bodies like enabling and disabling
limit // Controls the maximum request body size.
type // This is used to determine the type of middleware will parse
verify // It is an undefined function which used to verify the middleware parsing.
`;
`express.urlencoded([options]);`
options: `
extended // it allows to choose between parsing the URL-encoded data or the qs library
parameterLimit // It controls the no of params.
inflate // to manage the deflated bodies like enabling and disabling
limit // Controls the maximum request body size.
type // This is used to determine the type of middleware will parse
verify // It is an undefined function which used to verify the middleware parsing.
`;
```Application`````;
Properties```app.local`;
`app.locals.title = "My Cheatsheet";
console.dir(app.locals.title)`; `// Creating objects with local variables`
app.mountpath`
``app.mountpath``const admin = express()
admin.get('/', function(req,res){
console.log(admin.mountpath)
res.send('Admin Homepage')
})
app.use('', admin)`; `// Mounting a sub - app`
``Event``
`admin.on('mount', (parent){
console.log('Admin Mounted')
})` `// Mounting on a parent app`
``Methods``
`app.get('/', function(req, res){
res.send('GET request to message')
})` `// get requests to the specified path`
`app.post('/', function(req,res){
res.send('POST request to a webpage')
})` `// post request to the specified path`
`app.put('/', function(req,res){
res.send('PUT request to a webpage')
})` `// post request to the specified path`
`app.delete('/', function(req,res){
res.send('DELETE request to a webpage')
})` `// delete request to the specified path`
`app.all('/', function(req,res,next){
console.log('Accessing the secret section....')
next()
})` `// Routing all types of HTTP request`
`app.param('user', function(req,res,next){
User.find(id, function(err, user){
if(err){
next(err)
} else if (user){
req.user = user
next()
} else {
next(new Error('Failed to load user'))
}
})
})` `// Adding callback trigger to route parameters`
`app.use(function(req,res,next){
res.send('Hey There!')
})` `// To Invoke the middleware layer that you want to add`
```Request```
``Methods``
`req.get('content-type')` `// Returns the specified HTTP req header`
`req.accepts('html')` `// Checks if the specified content types are available or not`
`req.is('json')` `// Requests the matching content-type`
`var range = req.range(1000)
if (range.type === 'bytes'){
range.forEach(function(r){
// Your code
})
}` `// Range header parser`
``Properties``
`req.param('name')` `// Requests the param name when present`
`app.post('/', function (req, res, next) {
console.log(req.body)
res.json(req.body)
})` `// Data submitted in the request body`
`console.dir(req.cookies.name)` `// Contains cookies sent by the request`
`console.dir(req.query.q)` `// Query string parameter in the route`
`console.log(req.route)
res.send('GET')` `// Outputs all the layer, methods, path`
`console.dir(req.signedCookies.user)` `// Logs all the signed cookies sent by the request`
```Response```
``Methods``
`res.redirect('https://google.com')` `// Redirects to the intended page`
`res.send({message: 'Awesome Stuffs'})` `// Response to the webpage`
`res.json({alert: 'awesomecheatsheets'})` `// Response in JSON type`
`const file = req.params.name;
res.sendFile(file, options, function(err){
if(err){
next(err)
}else{
console.log('Sent:', file)
}
})` `// Sends file to the intended path`
`res.render('index')` `// Rendering the intended file`
```BodyParser```
`const BodyParser = require('body-parser')
app.use(BodyParser.json())
app.use(BodyParser.urlencoded({
extended: true
}))` `// Parses incoming request bodies`
================================================
FILE: backend/feathers.js
================================================
/* *******************************************************************************************
* FEATHERS.JS CHEATSHEET
* https://docs.feathersjs.com/api/readme.html
*
* 1. CORE: Feathers core functionality.
* 2. TRANSPORT: Expose a Feathers application as an API server.
* 3. CLIENT: More details on how to use Feathers on the client.
* 4. AUTHENTICATION: Feathers authentication mechanism.
* 5. DATABASE: Feathers common database adapter API and querying mechanism.
* ******************************************************************************************* */
/* *******************************************************************************************
* 1. CORE: Feathers core functionality.
* ******************************************************************************************* */
```
# Provides the ability to initialize new application instances
npm install @feathersjs/feathers --save
# Provides a set of standard error classes used by all other Feathers modules
npm install @feathersjs/errors --save
```
// --> APPLICATION <--
// https://docs.feathersjs.com/api/application.html
const feathers = require('@feathersjs/feathers');
const app = feathers(); // application initialization
app.mixins // contains a list of service mixins
app.use(path, service) // allows registering a service object on a given path
app.service(path) // returns the wrapped service object for the given path
app.hooks(hooks) // allows registration of application-level hooks
app.publish([event,], publisher) // registers a global event publisher
app.configure(callback) // runs a callback function that gets passed the application object
app.listen(port) // starts the application on the given port
app.setup([server]) // used to initialize all services by calling each services .setup(app, path) method (if available)
app.set(name, value) // assigns setting name to value
app.get(name) // retrieves the setting name
app.on(eventname, listener) // registers a listener method for the given eventname
app.emit(eventname, data) // emits the event eventname to all event listeners
app.removeListener(eventname, [ listener ]) // removes all or the given listener for eventname
// --> SERVICES <--
// https://docs.feathersjs.com/api/services.html
// "Services" are the heart of every Feathers application.
// Services are JavaScript objects (or instances of ES6 classes) that implement certain methods.
// Feathers itself will also add some additional methods and functionality to its services.
class MyService {
// Retrieves a list of all resources from the service.
// Provider parameters will be passed as params.query.
async find(params) {
return [];
}
// Retrieves a single resource with the given id from the service.
async get(id, params) {}
// Creates a new resource with data.
// The method should return the newly created data. data may also be an array.
async create(data, params) {}
// Replaces the resource identified by id with data.
// The method should return the complete, updated resource data.
// id can also be null when updating multiple records, with params.query containing the query criteria.
async update(id, data, params) {}
// Merges the existing data of the resource identified by id with the new data.
// id can also be null indicating that multiple resources should be patched with params.query containing the query criteria.
async patch(id, data, params) {}
// Removes the resource with id.
// The method should return the removed resource.
// id can also be null, which indicates the deletion of multiple resources, with params.query containing the query criteria.
async remove(id, params) {}
// A special method that initializes the service, passing an instance of the Feathers application
// and the path it has been registered on.
// For services registered before app.listen is invoked, the setup function of each registered service
// is called on invoking app.listen. For services registered after app.listen is invoked, setup is
// called automatically by Feathers when a service is registered.
setup(app, path) {}
}
params.query // contains the URL query parameters sent from the client
params.provider // for any service method call made through REST params.provider will be set to rest
app.use('/my-service', new MyService());
// Important: Always use the service returned by app.service(path)
const myService = app.service('my-service');
myService.hooks(hooks) // register hooks for this service
myService.publish([event,], publisher) // register an event publishing callback
myService.mixin(mixin) // extends the functionality of a service
myService.on(eventname, listener) // registers a listener method for the given eventname
myService.once(eventname, listener) // registers a listener method for the given eventname that will be triggered only one time
myService.emit(eventname, data) // emits the event eventname to all event listeners
myService.removeListener(eventname, [ listener ]) // removes all listeners (or the given listener) for eventname
// --> HOOKS <--
// https://docs.feathersjs.com/api/hooks.html
// Hooks are pluggable middleware functions that can be registered
// before, after or on errors of a service method. You can register a
// single hook function or create a chain of them to create complex work-flows.
app.service('my-service').hooks({
before: {
all: [
// Use normal functions
async function(context) { console.log('before all hook ran'); }
],
find: [
// Use ES6 arrow functions
context => console.log('before find hook 1 ran'),
async context => console.log('before find hook 2 ran')
],
async create (context) {
return context
},
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
// Here is an example for a very useful application hook that logs every service method error
// with the service and method name as well as the error stack
error(context) {
console.error(`Error in ${context.path} calling ${context.method} method`, context.error);
}
});
context.app // [read only] contains the Feathers application object
context.service // [read only] contains the service this hook currently runs on
context.path // [read only] contains the service name (or path) without leading or trailing slashes
context.method // [read only] contains the name of the service method (find, get, create, update...)
context.type // [read only] contains the hook type (one of before, after or error)
context.params // [writable] contains the service method parameters (including params.query)
context.id // [writable] contains the id for a get, remove, update and patch service method call
context.data // [writable] contains the data of a create, update and patch service method call
context.error // [writable] contains the error object that was thrown in a failed method call (only available in error hooks)
context.result // [writable] contains the result of the successful service method call (only available in after hooks)
context.dispatch // [writable and optional] contains a "safe" version of the data that should be sent to any client
// --> CHANNELS <--
// https://docs.feathersjs.com/api/channels.html
// A channel is an object that contains a number of connections.
// It can be created via app.channel and allows a connection to join or leave it.
app.channel(name) // when given a single name, returns an existing or new named channel
app.channel(name1, name2, ... nameN) // when given multiples names, will return a combined channel.
app.channels // returns a list of all existing channel names
channel.join(connection) // adds a connection to this channel
channel.leave(connection|fn) // removes a connection from this channel
channel.filter(fn) // returns a new channel filtered by a given function which gets passed the connection
channel.send(data) // returns a copy of this channel with customized data that should be sent for this event
channel.connections // contains a list of all connections in this channel
channel.length // returns the total number of connections in this channel
service.publish([event,] fn) // registers a publishing function for a specific service for a specific event or all events if no event name was given
app.publish([event,] fn) // registers an event publishing callback
app.on('connection', connection => {}) // fired every time a new real-time connection is established
app.on('disconnection', connection => {})
app.on('login', (authenticationResult, params, context) => {}) // sent by the authentication module and also contains the connection in the info object that is passed as the second parameter
/* *******************************************************************************************
* 2. TRANSPORT: Expose a Feathers application as an API server.
* ******************************************************************************************* */
```
# Contains Express framework integrations
npm install @feathersjs/express --save
# Allows to call service methods and receive real-time events
npm install @feathersjs/socketio --save
# Allows to call service methods and receive real-time events via Primus
npm install @feathersjs/primus --save
```
// --> EXPRESS <--
// https://docs.feathersjs.com/api/express.html
const feathers = require('@feathersjs/feathers');
const express = require('@feathersjs/express');
// Create an app that is a Feathers AND Express application
const app = express(feathers());
// If no Feathers application is passed, express() returns a plain Express application
// just like a normal call to Express would
const app = express();
app.use(path, service|mw) // registers either a service object or an Express middleware on the given path
app.listen(port) // will first call Express app.listen and then internally also call the Feathers app.setup(server)
app.setup(server) // usually called internally by app.listen but in the cases described below needs to be called explicitly
express.rest() // registers a Feathers transport mechanism that allows you to expose and consume services through a RESTful API.
app.configure(express.rest()) // configures the transport provider with a standard formatter sending JSON response via res.json
express.notFound() // returns middleware that returns a NotFound (404) Feathers error
express.errorHandler() // middleware that formats any error response to a REST call as JSON and sets the appropriate error code
app.use(express.errorHandler()) // set up the error handler with the default configuration
// --> SOCKET.IO <--
// https://docs.feathersjs.com/api/client/socketio.html
const feathers = require('@feathersjs/feathers');
const socketio = require('@feathersjs/socketio');
const app = feathers();
app.configure(socketio()); // sets up the Socket.io transport with the default configuration using either the server provided by app.listen or passed in app.setup(server)
app.configure(socketio(callback)) // sets up the Socket.io transport with the default configuration and call callback with the Socket.io server object
app.configure(socketio(options [, callback])) // sets up the Socket.io transport with the given Socket.io options object and optionally calls the callback
app.configure(socketio(port, [options], [callback])) // creates a new Socket.io server on a separate port. Options and a callback are optional
// --> PRIMUS <--
// https://docs.feathersjs.com/api/client/primus.html
app.configure(primus(options)) // sets up the Primus transport with the given Primus options
app.configure(primus(options, callback)) // sets up the Primus transport with the given Primus options and calls the callback with the Primus server instance
/* *******************************************************************************************
* 3. CLIENT: More details on how to use Feathers on the client.
* ******************************************************************************************* */
```
# Bundles the separate Feathers client side modules into one providing the code as ES5 (compatible with modern browsers)
# You do not have to install or load any of the other modules listed below
npm install @feathersjs/client --save
# Allows to connect to services through REST HTTP
npm install @feathersjs/rest-client --save
# Allows to connect to services through Socket.io
npm install @feathersjs/socketio-client --save
# Allows to connect to services through Primus
npm install @feathersjs/primus-client --save
# Allows you to easily authenticate against a Feathers server
npm install @feathersjs/authentication-client --save
```
// --> REST CLIENT <--
// https://docs.feathersjs.com/api/client/rest.html
rest([baseUrl]) // Initialize a client object with a base URL
app.configure(restClient.jquery(window.jQuery)); // connect to a service using jQuery
app.configure(restClient.request(requestClient)); // connect to a service using request
app.configure(restClient.superagent(superagent)); // connect to a service using Superagent
app.configure(restClient.axios(axios)); // connect to a service using Axios
app.configure(restClient.fetch(window.fetch)); // connect to a service using Fetch
// --> SOCKET.IO <--
// https://docs.feathersjs.com/api/client/socketio.html
socketio(socket) // initialize the Socket.io client using a given socket and the default options
socketio(socket, options) // initialize the Socket.io client using a given socket and the given options
// --> PRIMUS <--
// https://docs.feathersjs.com/api/client/primus.html
primus(socket) // initialize the Primus client using a given socket and the default options
primus(socket, options) // initialize the Primus client using a given socket and the given options
/* *******************************************************************************************
* 4. AUTHENTICATION: Feathers authentication mechanism.
* ******************************************************************************************* */
```
# Assists in using JWT for authentication
npm install @feathersjs/authentication --save
# Wraps the passport-local authentication strategy (username and password)
npm install @feathersjs/authentication-local --save
# Allows to use 180+ oAuth providers (Facebook, Google, Twitter etc.)
npm install @feathersjs/authentication-oauth --save
```
// --> SERVER <--
// https://docs.feathersjs.com/api/authentication/server.html
const options = {
"authentication": {
"secret": "CHANGE_ME", // The token signing secret
"entity": "user", // the entity that will be added to the request, socket, and context.params. (ie. req.user, socket.user, context.params.user)
"service": "users", // the service to look up the entity
"authStrategies": [ "jwt", "local" ], // The authentication strategies to allow to create a token
"jwtOptions": {
"header": { "typ": "access" }, // by default is an access token but can be any type
"audience": "https://yourdomain.com", // The resource server where the token is processed
"issuer": "feathers", // The issuing server, application or resource
"algorithm": "HS256", // the algorithm to use
"expiresIn": "1d" // the access token expiry
}
}
}
const { AuthenticationService, JWTStrategy } = require('@feathersjs/authentication');
let authService = new AuthenticationService(app);
service.register('jwt', new JWTStrategy());
app.use('/authentication', authService);
app.configure(expressOauth());
app.get('defaultAuthentication') // The name of the default authentication service
authService = app.service('authentication') // service for creating JWT (implements only the create and remove methods)
authService.hooks({ before }) // registers hooks for this service
authService.hooks({ after }) // registers hooks for this service
new AuthenticationService(app) // Create a new authentication service
class MyAuthenticationService extends AuthenticationService {} // Customize the authentication service
authService.authenticate(data, params, ...strategies) // Authenticate with strategies
authService.create(data, params) // Authenticate with data and params
authService.create({ // Authenticate and create a JWT using the local strategy email/password
strategy: 'local',
email: 'hello@feathersjs.com',
password: 'supersecret'
});
authService.remove(id, params) // removes the JWT token (mostly exists for the logout process)
authService.configuration // The current configuration
authService.register(name, strategy) // Register a new authentication strategy
authService.createAccessToken(payload) // Create a new access token with payload
authService.verifyAccessToken(accessToken) // Verify an existing access token
authService.getTokenOptions(authResult, params) // Get the options for a token
authService.getPayload(authResult, params) // Return the payload for an authentication result
authService.parse(req, res, ...strategies) // Parse an HTTP request and response with using a list of strategies
app.on('login', callback)) // emits an event whenever a client successfully authenticates
app.on('logout', callback)) // emits an event whenever a client successfully logout
// --> CLIENT <--
// https://docs.feathersjs.com/api/authentication/client.html
const options = {
storage: window.localStorage, // The storage to store the access token
path: '/authentication', // The path of the authentication service
locationKey: 'access_token', // The name of the window hash parameter to parse for an access token from the window.location. Usually used by the oAuth flow.
locationErrorKey: 'error', // The name of the window hash parameter to parse for authentication errors. Usually used by the oAuth flow.
jwtStrategy: 'jwt', // The access token authentication strategy
storageKey: 'feathers-jwt', // Key for storing the token in e.g. localStorage
header: 'Authorization', // Name of the accessToken header
scheme: 'Bearer', // The HTTP header scheme
Authentication: AuthenticationClient // Allows to provide a customized authentication client class
}
app.configure(auth(options)) // configure the authentication plugin with the given options
app.reAuthenticate() // authenticates using the JWT from the storage
app.authenticate(options) // authenticate with a Feathers server by passing a strategy and other properties as credentials
app.logout() // removes the JWT accessToken from storage on the client
const authenticationInfo = await app.get('authentication'); // The authenticatoin information (like the user)
app.on('login', callback) // emits an event whenever the client successfully authenticates
app.on('logout', callback) // emits an event whenever the client successfully authenticates
// --> LOCAL (EMAIL & PASSWORD) <--
// https://docs.feathersjs.com/api/authentication/local.html
const { LocalStrategy } = require('@feathersjs/authentication-local');
const options = {
usernameField: 'email', // Name of the username field in the (e.g. 'email')
passwordField: 'password', // Name of the password field (e.g. 'password')
hashSize: 10, // The BCrypt hash size
errorMessage: 'Invalid login', // The error message to return on errors
entityUsernameField: usernameField, // Name of the username field on the entity if authentication request data and entity field names are different
entityPasswordField: passwordField // Name of the password field on the entity if authentication request data and entity field names are different
}
authService.register('local', new LocalStrategy());
local.hooks.hashPassword() // hashes plain text passwords before they are saved to the database
local.hooks.protect('password') // makes sure that protected fields don't get sent to a client
// --> OAUTH <--
// https://docs.feathersjs.com/api/authentication/oauth.html
const { expressOauth, OAuthStrategy } = require('@feathersjs/authentication-oauth');
class GitHubStrategy extends OAuthStrategy {
async getEntityData(profile) {
const baseData = await super.getEntityData(profile);
return {
...baseData,
email: profile.email
};
}
}
authService.register('github', new MyGitHubStrategy());
const options = {
authentication: {
oauth: {
redirect: '/', // The redirect after a successful login
github: { // The per-strategy configuration
key: '',
secret: ''
}
}
}
}
app.configure(expressOauth(options));
/* *******************************************************************************************
* 5. DATABASE: Feathers common database adapter API and querying mechanism.
* ******************************************************************************************* */
```
# [MEMORY/FILESYSTEM] In-memory database adapter
npm install feathers-memory --save
# [MEMORY/FILESYSTEM] Database adapter for NeDB an in-memory or file system based standalone database
npm install feathers-nedb --save
# [MEMORY/FILESYSTEM] Adapter for Client side Feathers that can use the browsers LocalStorage or ReactNative's AsyncStorage
npm install feathers-localstorage --save
# [SQL] Adapter for KnexJS, an SQL query builder for NodeJS supporting PostgreSQL, MySQL, SQLite and MSSQL
npm install feathers-knex --save
# [SQL] Adapter for Sequelize an ORM for NodeJS supporting PostgreSQL, MySQL, SQLite and MSSQL
npm install feathers-sequelize --save
# [NOSSQL] Database adapter for MongoDB using the official NodeJS database driver
npm install feathers-mongodb --save
# [NOSSQL] Database adapter for Mongoose an Object Modelling library for NodeJS and MongoDB
npm install feathers-mongoose --save
# [NOSSQL] Database adapter for Elasticsearch
npm install feathers-elasticsearch --save
# [NOSSQL] Database adapter for RethinkDB a real-time database.
npm install feathers-rethinkdb --save
```
// --> COMMON API <--
// https://docs.feathersjs.com/api/databases/common.html
const service = require('feathers-');
app.use('/messages', service({
id: undefined, // (optional) name of the id field property (usually set by default to id or _id)
events: undefined, // (optional) list of custom service events sent by this service
paginate: { // (optional) a pagination object containing a default and max page size
default: undefined, // sets the default number of items when $limit is not set
max: undefined // sets the maximum allowed number of items per page (even if the $limit query parameter is set higher)
},
whitelist: [], // A list of additional non-standard query parameters to allow (e.g [ '$regex', '$populate' ])
multi: true // Allow create with arrays and update and remove with id null to change multiple items
}));
adapter.find() // returns a list of all records matching the query in params.query using the common querying mechanism
adapter.get(id, params) // retrieves a single record by its unique identifier (the field set in the id option during initialization)
adapter.create(data, params) // creates a new record with data. data can also be an array to create multiple records
adapter.update(id, data, params) // completely replaces a single record identified by id with data. Does not allow replacing multiple records (id can't be null). id can not be changed.
adapter.patch(id, data, params) // merges a record identified by id with data. id can be null to allow replacing multiple records (all records that match params.query the same as in .find). id can not be changed
adapter.remove(id, params) // removes a record identified by id. id can be null to allow removing multiple records (all records that match params.query the same as in .find)
// Hook-less
adapter._find()
adapter._get(id, params)
adapter._create(data, params)
adapter._update(id, data, params)
adapter._patch(id, data, params)
adapter._remove(id, params)
// --> QUERYING <--
// https://docs.feathersjs.com/api/databases/querying.html
app.service('messages').find({
query: {
$limit: 2, // will return only the number of results you specify
$select: [ 'text', 'userId' ], // allows to pick which fields to include in the result
$skip: 2, // will skip the specified number of results
$sort: { // will sort based on the object you provide. It can contain a list of properties by which to sort mapped to the order
createdAt: -1
},
$or: [ // find all records that match any of the given criteria
{ archived: { $ne: true } },
{ roomId: 2 }
],
read: false, // compared directly for equality
roomId: {
$in: [ 2, 5 ], // find all records where the property does match any of the given values
$nin: [ 1, 3 ] // find all records where the property does not match any of the given values
},
createdAt: {
$lt: new Date().getTime(), // find all records where the value is less to a given value
$lte: new Date().getTime(), // find all records where the value is less and equal to a given value
$gt: new Date().getTime(), // find all records where the value is more to a given value
$gte: new Date().getTime(), // find all records where the value is more and equal to a given value
},
archived: {
$ne: true // find all records that do not equal the given property value
}
}
});
// With pagination enabled, to just get the number of available records set $limit to 0.
// This will only run a (fast) counting query against the database and return a page object with
// the total and an empty data array.
/* *******************************************************************************************
* 5. APPLICATION ARCHITECTURE
* ******************************************************************************************* */
// .
// ├── config/ # contains the configuration files for the app
// │ ├── default.json # default configuration variables
// │ ├── production.json # override default configurations variables when NODE_ENV=production
// │ └── ...
// │
// ├── node_modules/ # project dependencies using NPM or Yarn
// │ └── ...
// │
// ├── public/ # contains static files to be served
// │ └── ...
// │
// ├── src/ # contains the Feathers server code
// │ ├── hooks/ # contains our custom hooks
// │ │ └── ...
// │ ├── middleware/ # contains our Express middlewares
// │ │ └── ...
// │ ├── services/ # contains our services
// │ │ └── ...
// │ │
// │ ├── index.js # is used to load and start the application
// │ ├── app.js # configures our Feathers application
// │ ├── app.hooks.js # contains hooks which that run for all services
// │ └── channels.js # set up Feathers event channels
// ├── tests/ # contains Mocha test files for the app, hooks and services
// │ └── ...
// ├── .editorconfig # helps developers define and maintain consistent coding styles
// ├── .eslintrc.json # eslint configuration
// └── package.json # express server for production
================================================
FILE: backend/laravel.php
================================================
engine = 'InnoDB'; // Specify the table storage engine (MySQL).
$table->charset = 'utf8'; // Specify a default character set for the table (MySQL).
$table->collation = 'utf8_unicode_ci'; // Specify a default collation for the table (MySQL).
$table->temporary(); // Create a temporary table (except SQL Server).
// COLUMN TYPES
$table->bigIncrements('id'); // Auto-incrementing UNSIGNED BIGINT (primary key) equivalent column.
$table->bigInteger('votes'); // BIGINT equivalent column.
$table->binary('data'); // BLOB equivalent column.
$table->boolean('confirmed'); // BOOLEAN equivalent column.
$table->char('name', 100); // CHAR equivalent column with an optional length.
$table->date('created_at'); // DATE equivalent column.
$table->dateTime('created_at'); // DATETIME equivalent column.
$table->dateTimeTz('created_at'); // DATETIME (with timezone) equivalent column.
$table->decimal('amount', 8, 2); // DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
$table->double('amount', 8, 2); // DOUBLE equivalent column with a precision (total digits) and scale (decimal digits).
$table->enum('level', ['easy', 'hard']); // ENUM equivalent column.
$table->float('amount', 8, 2); // FLOAT equivalent column with a precision (total digits) and scale (decimal digits).
$table->geometry('positions'); // GEOMETRY equivalent column.
$table->geometryCollection('positions'); // GEOMETRYCOLLECTION equivalent column.
$table->increments('id'); // Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column.
$table->integer('votes'); // INTEGER equivalent column.
$table->ipAddress('visitor'); // IP address equivalent column.
$table->json('options'); // JSON equivalent column.
$table->jsonb('options'); // JSONB equivalent column.
$table->lineString('positions'); // LINESTRING equivalent column.
$table->longText('description'); // LONGTEXT equivalent column.
$table->macAddress('device'); // MAC address equivalent column.
$table->mediumIncrements('id'); // Auto-incrementing UNSIGNED MEDIUMINT (primary key) equivalent column.
$table->mediumInteger('votes'); // MEDIUMINT equivalent column.
$table->mediumText('description'); // MEDIUMTEXT equivalent column.
$table->morphs('taggable'); // Adds taggable_id UNSIGNED BIGINT and taggable_type VARCHAR equivalent columns.
$table->uuidMorphs('taggable'); // Adds taggable_id CHAR(36) and taggable_type VARCHAR(255) UUID equivalent columns.
$table->multiLineString('positions'); // MULTILINESTRING equivalent column.
$table->multiPoint('positions'); // MULTIPOINT equivalent column.
$table->multiPolygon('positions'); // MULTIPOLYGON equivalent column.
$table->nullableMorphs('taggable'); // Adds nullable versions of morphs() columns.
$table->nullableUuidMorphs('taggable'); // Adds nullable versions of uuidMorphs() columns.
$table->nullableTimestamps(); // Alias of timestamps() method.
$table->point('position'); // POINT equivalent column.
$table->polygon('positions'); // POLYGON equivalent column.
$table->rememberToken(); // Adds a nullable remember_token VARCHAR(100) equivalent column.
$table->set('flavors', ['strawberry', 'vanilla']); // SET equivalent column.
$table->smallIncrements('id'); // Auto-incrementing UNSIGNED SMALLINT (primary key) equivalent column.
$table->smallInteger('votes'); // SMALLINT equivalent column.
$table->softDeletes(); // Adds a nullable deleted_at TIMESTAMP equivalent column for soft deletes.
$table->softDeletesTz(); // Adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column for soft deletes.
$table->string('name', 100); // VARCHAR equivalent column with a optional length.
$table->text('description'); // TEXT equivalent column.
$table->time('sunrise'); // TIME equivalent column.
$table->timeTz('sunrise'); // TIME (with timezone) equivalent column.
$table->timestamp('added_on'); // TIMESTAMP equivalent column.
$table->timestampTz('added_on'); // TIMESTAMP (with timezone) equivalent column.
$table->timestamps(); // Adds nullable created_at and updated_at TIMESTAMP equivalent columns.
$table->timestampsTz(); // Adds nullable created_at and updated_at TIMESTAMP (with timezone) equivalent columns.
$table->tinyIncrements('id'); // Auto-incrementing UNSIGNED TINYINT (primary key) equivalent column.
$table->tinyInteger('votes'); // TINYINT equivalent column.
$table->unsignedBigInteger('votes'); // UNSIGNED BIGINT equivalent column.
$table->unsignedDecimal('amount', 8, 2); // UNSIGNED DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
$table->unsignedInteger('votes'); // UNSIGNED INTEGER equivalent column.
$table->unsignedMediumInteger('votes'); // UNSIGNED MEDIUMINT equivalent column.
$table->unsignedSmallInteger('votes'); // UNSIGNED SMALLINT equivalent column.
$table->unsignedTinyInteger('votes'); // UNSIGNED TINYINT equivalent column.
$table->uuid('id'); // UUID equivalent column.
$table->year('birth_year'); // YEAR equivalent column.
// COLUMN MODIFIERS
$table->someType()->after('column'); // Place the column "after" another column (MySQL)
$table->someType()->autoIncrement(); // Set INTEGER columns as auto-increment (primary key)
$table->someType()->charset('utf8'); // Specify a character set for the column (MySQL)
$table->someType()->collation('utf8_unicode_ci'); // Specify a collation for the column (MySQL/SQL Server)
$table->someType()->comment('my comment'); // Add a comment to a column (MySQL/PostgreSQL)
$table->someType()->default($value); // Specify a "default" value for the column
$table->someType()->first(); // Place the column "first" in the table (MySQL)
$table->someType()->nullable($value = true); // Allows (by default) NULL values to be inserted into the column
$table->someType()->storedAs($expression); // Create a stored generated column (MySQL)
$table->someType()->unsigned(); // Set INTEGER columns as UNSIGNED (MySQL)
$table->someType()->useCurrent(); // Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value
$table->someType()->virtualAs($expression); // Create a virtual generated column (MySQL)
$table->someType()->generatedAs($expression); // Create an identity column with specified sequence options (PostgreSQL)
$table->someType()->always(); // Defines the precedence of sequence values over input for an identity column (PostgreSQL)
// UPDATING COLUMNS
$table->someType()->change(); // Allows you to modify some existing column types to a new type or modify the column's attributes.
$table->renameColumn('from', 'to'); // Rename a column
$table->dropColumn('column'); // Drop a given column (accepts an array of columns).
$table->dropRememberToken(); // Drop the remember_token column.
$table->dropSoftDeletes(); // Drop the deleted_at column.
$table->dropSoftDeletesTz(); // Alias of dropSoftDeletes() method.
$table->dropTimestamps(); // Drop the created_at and updated_at columns.
$table->dropTimestampsTz(); // Alias of dropTimestamps() method.
// INDEXES
$table->primary('id'); // Adds a primary key.
$table->primary(['id', 'parent_id']); // Adds composite keys.
$table->unique('email'); // Adds a unique index.
$table->index('state'); // Adds a plain index.
$table->spatialIndex('location'); // Adds a spatial index. (except SQLite)
$table->dropPrimary('users_id_primary'); // Drop a primary key from the "users" table.
$table->dropUnique('users_email_unique'); // Drop a unique index from the "users" table.
$table->dropIndex('geo_state_index'); // Drop a basic index from the "geo" table.
$table->dropSpatialIndex('geo_location_spatialindex'); // Drop a spatial index from the "geo" table (except SQLite).
// FOREIGN KEY CONSTRAINTS
$table->foreign('user_id')->references('id')->on('users'); // Create foreign key constraints.
$table->dropForeign('posts_user_id_foreign'); // Drop foreign key (accepts an array of strings).
Schema::enableForeignKeyConstraints(); // Enable foreign key constraints within your migrations.
Schema::disableForeignKeyConstraints(); // Disable foreign key constraints within your migrations.
/********************************************************************************************
* COLLECTION ELOQUENT METHODS
* https://laravel.com/docs/5.7/collections
********************************************************************************************/
all
average
avg
chunk
collapse
combine
concat
contains
containsStrict
count
crossJoin
dd
diff
diffAssoc
diffKeys
dump
each
eachSpread
every
except
filter
first
firstWhere
flatMap
flatten
flip
forget
forPage
get
groupBy
has
implode
intersect
intersectByKeys
isEmpty
isNotEmpty
keyBy
keys
last
macro
make
map
mapInto
mapSpread
mapToGroups
mapWithKeys
max
median
merge
min
mode
nth
only
pad
partition
pipe
pluck
pop
prepend
pull
push
put
random
reduce
reject
reverse
search
shift
shuffle
slice
some
sort
sortBy
sortByDesc
sortKeys
sortKeysDesc
splice
split
sum
take
tap
times
toArray
toJson
transform
union
unique
uniqueStrict
unless
unlessEmpty
unlessNotEmpty
unwrap
values
when
whenEmpty
whenNotEmpty
where
whereStrict
whereBetween
whereIn
whereInStrict
whereInstanceOf
whereNotBetween
whereNotIn
whereNotInStrict
wrap
zip
/********************************************************************************************
* HTTP TESTS
* https://laravel.com/docs/5.7/http-tests
********************************************************************************************/
$response->assertStatus($code); // Assert that the response has a given code.
$response->assertForbidden(); // Assert that the response has a forbidden status code.
$response->assertNotFound(); // Assert that the response has a not found status code.
$response->assertOk(); // Assert that the response has a 200 status code.
$response->assertSuccessful(); // Assert that the response has a successful status code.
$response->assertRedirect($uri); // Assert that the response is a redirect to a given URI.
$response->assertHeader($headerName, $value = null); // Assert that the given header is present on the response.
$response->assertHeaderMissing($headerName); // Assert that the given header is not present on the response.
$response->assertExactJson(array $data); // Assert that the response contains an exact match of the given JSON data.
$response->assertJson(array $data); // Assert that the response contains the given JSON data.
$response->assertJsonCount($count, $key = null); // Assert that the response JSON has an array with the expected number of items at the given key.
$response->assertJsonFragment(array $data); // Assert that the response contains the given JSON fragment.
$response->assertJsonMissing(array $data); // Assert that the response does not contain the given JSON fragment.
$response->assertJsonMissingExact(array $data); // Assert that the response does not contain the exact JSON fragment.
$response->assertJsonMissingValidationErrors($keys); // Assert that the response has no JSON validation errors for the given keys.
$response->assertJsonStructure(array $structure); // Assert that the response has a given JSON structure.
$response->assertJsonValidationErrors($keys); // Assert that the response has the given JSON validation errors for the given keys.
$response->assertDontSee($value); // Assert that the given string is not contained within the response.
$response->assertDontSeeText($value); // Assert that the given string is not contained within the response text.
$response->assertSee($value); // Assert that the given string is contained within the response.
$response->assertSeeInOrder(array $values); // Assert that the given strings are contained in order within the response.
$response->assertSeeText($value); // Assert that the given string is contained within the response text.
$response->assertSeeTextInOrder(array $values); // Assert that the given strings are contained in order within the response text.
$response->assertCookie($cookieName, $value = null); // Assert that the response contains the given cookie.
$response->assertCookieExpired($cookieName); // Assert that the response contains the given cookie and it is expired.
$response->assertCookieNotExpired($cookieName); // Assert that the response contains the given cookie and it is not expired.
$response->assertCookieMissing($cookieName); // Assert that the response does not contains the given cookie.
$response->assertPlainCookie($cookieName, $value = null); // Assert that the response contains the given cookie (unencrypted).
$response->assertSessionHas($key, $value = null); // Assert that the session contains the given piece of data.
$response->assertSessionHasAll(array $data); // Assert that the session has a given list of values.
$response->assertSessionHasErrors(array $keys, $format = null, $errorBag = 'default'); // Assert that the session contains an error for the given field.
$response->assertSessionHasErrorsIn($errorBag, $keys = [], $format = null); // Assert that the session has the given errors.
$response->assertSessionHasNoErrors(); // Assert that the session has no errors.
$response->assertSessionDoesntHaveErrors($keys = [], $format = null, $errorBag = 'default'); // Assert that the session has no errors for the given keys.
$response->assertSessionMissing($key); // Assert that the session does not contain the given key.
$response->assertViewHas($key, $value = null); // Assert that the response view was given a piece of data.
$response->assertViewHasAll(array $data); // Assert that the response view has a given list of data.
$response->assertViewIs($value); // Assert that the given view was returned by the route.
$response->assertViewMissing($key); // Assert that the response view is missing a piece of bound data.
$this->assertAuthenticated($guard = null); // Assert that the user is authenticated.
$this->assertGuest($guard = null); // Assert that the user is not authenticated.
$this->assertAuthenticatedAs($user, $guard = null); // Assert that the given user is authenticated.
$this->assertCredentials(array $credentials, $guard = null); // $this->assertCredentials(array $credentials, $guard = null).
$this->assertInvalidCredentials(array $credentials, $guard = null); // Assert that the given credentials are invalid.
/********************************************************************************************
* LARAVEL VALET COMMANDS
* https://laravel.com/docs/6.0/valet
********************************************************************************************/
valet install // Install the Valet daemon.
valet uninstall // Uninstall the Valet daemon.
valet use php@7.2 // Allows you to switch between php versions.
valet start // Start the Valet daemon.
valet stop // Stop the Valet daemon.
valet restart // Restart the Valet daemon.
valet park // Register your current working directory as a path which Valet should search for sites.
valet forget // Run this command from a "parked" directory to remove it from the parked directory list.
valet paths // View all of your "parked" paths.
valet link // Link a single site in the current directory and not the entire directory.
valet unlink // Unlink a single site in the current directory
valet links // View all of your "linked" paths.
valet secure // Serve site into https
valet unsecure // Revert back to http
valet log // View a list of logs which are written by Valet's services.
valet trust // Add sudoers files for Brew and Valet to allow Valet commands to be run without prompting for passwords.
valet tld // Update tld for your domains (default to test).
valet share // Share your site with the world.
================================================
FILE: backend/moleculer.js
================================================
/* *******************************************************************************************
* MOLECULER MICROSERVICES FRAMEWORK - CORE CHEATSHEET
* http://moleculer.services/0.12/docs/
*
* Version: 0.12.x
* ******************************************************************************************* */
/* *******************************************************************************************
* Install Moleculer
* ******************************************************************************************* */
```bash
npm i moleculer
```
/* *******************************************************************************************
* SERVICE BROKER OPTIONS
* ******************************************************************************************* */
// All ServiceBroker options with default values
const broker = new ServiceBroker({
namespace: "", // Namespace for node segmentation
nodeID: null, // NodeID. Default value is generated from hostname and PID
logger: null, // Logger instance.
logLevel: null, // Log level
logFormatter: "default", // Log formatter. Options: "default", "simple"
transporter: null, // Transporter config
requestTimeout: 0 * 1000, // Timeout of requests
requestRetry: 0, // Retries for requests
maxCallLevel: 0, // Maximum calling level.
heartbeatInterval: 5, // Heartbeat sending interval in seconds
heartbeatTimeout: 15, // Heartbeat timeout in seconds
disableBalancer: false, // Disable the built-in Moleculer balancer
registry: { // Service Registry options
strategy: "RoundRobin", // Invocation strategy
strategyOptions: null, // Strategy options
preferLocal: true // Prefer local invocations
},
circuitBreaker: { // Circuit-breaker options
enabled: false, // Enable circuit-breaker
maxFailures: 3, // Maximum failures
halfOpenTime: 10 * 1000, // Half-open time interval
failureOnTimeout: true, // Failure on timeouts
failureOnReject: true // Failure on rejects
},
transit: { // Transit options
maxQueueSize: 50 * 1000 // Max items in outgoing queue
},
cacher: null, // Cacher config
serializer: null, // Serializer config
validation: true, // Enable params validation
validator: null, // Validator instance
metrics: false, // Enable metrics
metricsRate: 1, // Metrics rate
statistics: false, // Enable statistics
internalServices: true, // Load internal ($node) services
hotReload: false, // Hot-reload services
middlewares: null, // List of middlewares
replCommands: null, // Custom REPL commands
ServiceFactory: null, // Custom Service factory class
ContextFactory: null // Custom Context factory class
});
/* *******************************************************************************************
* SERVICE BROKER METHODS
* ******************************************************************************************* */
// Broker properties
broker.Promise // Pointer to Bluebird Promise lib
broker.namespace // Namespace from options
broker.nodeID // Local NodeID
broker.logger // Logger instance
broker.cacher // Cacher instance
broker.serializer // Serializer instance
broker.validator // Validator instance
// Broker methods
broker.start(); // Start broker & all services. Returns a Promise
broker.stop(); // Stop broker & all services. Returns a Promise
broker.fatal(message, err, needExit = true); // Fired a fatal error.
broker.repl(); // Switch broker to REPL mode.
broker.getLogger(module, service, version); // Create a custom logger instance for modules
broker.loadServices(folder, fileMask); // Load all services from directory
broker.loadService(filePath); // Load a service from a file
broker.createService(schema, schemaMods); // Create a local service from schema
broker.destroyService(service); // Destroy a local service
broker.getLocalService(name, version); // Get a local service instance by name
// Wait for services. Returns a Promise
await broker.waitForServices(serviceNames, timeout, interval);
await broker.waitForServices(["posts", "users"], 5000);
await broker.waitForServices({
name: "posts", version: 2,
name: "users", version: 1
}, 5000);
broker.use(...middlewares); // Register middlewares
broker.call(actionName, params, opts); // Call a service
broker.mcall(def); // Multiple service calls
broker.emit(eventName, payload, groups); // Emit a balanced event
broker.broadcast(eventName, payload, groups = null) // Broadcast an event
broker.broadcastLocal(eventName, payload, groups = null) // Broadcast an event to local services
broker.sendPing(nodeID); // Ping a remote node
broker.MOLECULER_VERSION // Version number of Moleculer lib
broker.PROTOCOL_VERSION // Version number of Moleculer protocol
/* *******************************************************************************************
* BROKER SERVICE CALLS
* ******************************************************************************************* */
// Call the "users.get" service with params
broker.call("users.get", { id: 150 }).then(user => console.log(user));
// Call with async/await
const user = await broker.call("users.get", { id: 150});
// Call with calling options
const user = await broker.call("users.get", { id: 150}, { timeout: 5000, retryCount: 3 });
// Direct call to a remote node
const info = await broker.call("$node.services", null, { nodeID: "node-123" });
// Multiple calls with array def
const [posts, users] = await broker.mcall([
{ action: "posts.find", params: { limit: 5, offset: 0 } },
{ action: "users.find", params: { limit: 5, sort: "username" }, opts: { timeout: 500 } }
]);
// Multip calls with object def
const res = await broker.mcall({
posts: { action: "posts.find", params: { limit: 5, offset: 0 } },
users: { action: "users.find", params: { limit: 5, sort: "username" }, opts: { timeout: 500 } }
});
console.log(res.posts, res.users);
/* *******************************************************************************************
* BROKER EVENTS
* ******************************************************************************************* */
// Send a balanced event with payload
broker.emit("user.created", { user: user });
// Send a balanced event only for "mail" and "payment" service (only one instance)
broker.emit("user.created", { user: user }, ["mail", "payment"]);
// Send a broadcast event (for all service instances)
broker.broadcast("user.created", { user: user });
// Send a broadcast event only for "mail" and "payment" services (all instances)
broker.broadcast("user.created", { user: user }, ["mail", "payment"]);
/* *******************************************************************************************
* NATS TRANSPORTER
* Requirement: `npm i nats`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "NATS"
});
// With URI
const broker = new ServiceBroker({
transporter: "nats://localhost:4222"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "NATS",
options: {
url: "nats://localhost:4222",
user: "admin",
pass: "1234"
}
}
});
// With TLS (https://github.com/nats-io/node-nats#tls)
const broker = new ServiceBroker({
transporter: {
type: "NATS",
options: {
url: "nats://localhost:4222",
tls: {
key: fs.readFileSync('./client-key.pem'),
cert: fs.readFileSync('./client-cert.pem'),
ca: [ fs.readFileSync('./ca.pem') ]
}
}
}
});
/* *******************************************************************************************
* REDIS TRANSPORTER
* Requirement: `npm i ioredis`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "Redis"
});
// With URI
const broker = new ServiceBroker({
transporter: "redis://redis-server:6379"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "Redis",
options: {
port: 6379, // Redis port
host: 'redis-server', // Redis host
family: 4, // 4 (IPv4) or 6 (IPv6)
password: 'auth', // Password
db: 0 // Database index
}
}
});
/* *******************************************************************************************
* MQTT TRANSPORTER
* Requirement: `npm i mqtt`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "MQTT"
});
// With URI
const broker = new ServiceBroker({
transporter: "mqtt://mqtt-server:1883"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "MQTT",
options: {
host: "mqtt-server",
port: 1883,
username: "admin",
password: "1234"
}
}
});
/* *******************************************************************************************
* AMQP TRANSPORTER
* Requirement: `npm i amqplib`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "AMQP"
});
// With URI
const broker = new ServiceBroker({
transporter: "amqp://rabbitmq-server:5672"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "AMQP",
options: {
url: "amqp://user:pass@rabbitmq-server:5672",
eventTimeToLive: 5000,
prefetch: 1
}
}
});
/* *******************************************************************************************
* KAFKA TRANSPORTER
* Requirement: `npm i kafka-node`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "Kafka"
});
// With URI
const broker = new ServiceBroker({
transporter: "kafka://192.168.51.29:2181"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "kafka",
options: {
host: "192.168.51.29:2181",
// KafkaClient options. More info: https://github.com/SOHU-Co/kafka-node#clientconnectionstring-clientid-zkoptions-noackbatchoptions-ssloptions
client: {
zkOptions: undefined,
noAckBatchOptions: undefined,
sslOptions: undefined
},
// KafkaProducer options. More info: https://github.com/SOHU-Co/kafka-node#producerclient-options-custompartitioner
producer: {},
customPartitioner: undefined,
// ConsumerGroup options. More info: https://github.com/SOHU-Co/kafka-node#consumergroupoptions-topics
consumer: {
},
// Advanced options for `send`. More info: https://github.com/SOHU-Co/kafka-node#sendpayloads-cb
publish: {
partition: 0,
attributes: 0
}
}
}
});
/* *******************************************************************************************
* NATS STREAMING TRANSPORTER
* Requirement: `npm i node-nats-streaming`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "STAN"
});
// With URI
const broker = new ServiceBroker({
transporter: "stan://192.168.0.120:4222"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "STAN",
options: {
url: "stan://127.0.0.1:4222",
clusterID: "my-cluster"
}
}
});
/* *******************************************************************************************
* TCP STREAMING TRANSPORTER
* No requirements
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "TCP"
});
// With static node list
const broker = new ServiceBroker({
transporter: "tcp://172.17.0.1:6000/node-1,172.17.0.2:6000/node-2"
});
const broker = new ServiceBroker({
nodeID: "node-1",
transporter: {
type: "TCP",
options: {
udpDiscovery: false,
urls: [
"172.17.0.1:6000/node-1",
"172.17.0.2:6000/node-2",
"172.17.0.3:6000/node-3"
]
}
}
});
// With full options
const broker = new ServiceBroker({
logger: true,
transporter: {
type: "TCP",
options: {
// Enable UDP discovery
udpDiscovery: true,
// Reusing UDP server socket
udpReuseAddr: true,
// UDP port
udpPort: 4445,
// UDP bind address
udpBindAddress: null,
// UDP sending period
udpPeriod: 5,
// Multicast address.
udpMulticast: "239.0.0.0",
// Multicast TTL setting
udpMulticastTTL: 1,
// Send broadcast
udpBroadcast: false,
// TCP server port. Null or 0 means random port
port: null,
// Static remote nodes address list (when UDP discovery is not available)
urls: null,
// Use hostname as preffered connection address
useHostname: true,
// Gossip sending period in seconds
gossipPeriod: 2,
// Maximum enabled outgoing connections. If reach, close the old connections
maxConnections: 32,
// Maximum TCP packet size
maxPacketSize: 1 * 1024 * 1024
}
}
});
/* *******************************************************************************************
* CACHERS
* http://moleculer.services/docs/cachers.html
* ******************************************************************************************* */
// Memory cacher
const broker = new ServiceBroker({
cacher: "Memory"
});
// or
const broker = new ServiceBroker({
cacher: true
});
// Memory cacher with options
const broker = new ServiceBroker({
cacher: {
type: "Memory",
options: {
ttl: 30
}
}
});
// Redis cacher
const broker = new ServiceBroker({
cacher: "Redis"
});
// Redis cacher with URI
const broker = new ServiceBroker({
cacher: "redis://redis-server:6379"
});
// Redis cacher with options
const broker = new ServiceBroker({
cacher: {
type: "Redis",
options: {
prefix: "MOL",
redis: {
host: "redis",
port: 6379,
password: "1234",
db: 0
}
}
}
});
/* *******************************************************************************************
* Manual caching
* ******************************************************************************************* */
// Save to cache
broker.cacher.set("mykey.a", { a: 5 });
// Get from cache
const obj = await broker.cacher.get("mykey.a");
// Remove entry from cache
broker.cacher.del("mykey.a");
// Clean all 'mykey' entries
broker.cacher.clean("mykey.*");
// Clean all entries
broker.cacher.clean();
/* *******************************************************************************************
* SERIALIZER
* http://moleculer.services/docs/serializers.html
* ******************************************************************************************* */
// JSON serializer (default)
const broker = new ServiceBroker({
serializer: "JSON"
});
// Avro serializer (need `npm i avsc`)
const broker = new ServiceBroker({
serializer: "Avro"
});
// Protocol Buffer serializer (need `npm i protobufjs`)
const broker = new ServiceBroker({
serializer: "ProtoBuf"
});
// MsgPack serializer (need `npm i msgpack5`)
const broker = new ServiceBroker({
serializer: "MsgPack"
});
/* *******************************************************************************************
* STRATEGY
* ******************************************************************************************* */
// Round-robin strategy (default)
const broker = new ServiceBroker({
registry: {
strategy: "RoundRobin"
}
});
// Random strategy
const broker = new ServiceBroker({
registry: {
strategy: "Random"
}
});
// CPU usage-based strategy
const broker = new ServiceBroker({
registry: {
strategy: "CpuUsageStrategy"
}
});
// CPU usage-based strategy with options
const broker = new ServiceBroker({
registry: {
strategy: "CpuUsageStrategy",
strategyOptions: {
sampleCount: 3,
lowCpuUsage: 10
}
}
});
/* *******************************************************************************************
* LOGGER
* http://moleculer.services/docs/logger.html
* ******************************************************************************************* */
// Logger methods
broker.logger.fatal();
broker.logger.error();
broker.logger.warn();
broker.logger.info();
broker.logger.debug();
broker.logger.trace();
// Custom log formatter
const broker = new ServiceBroker({
logger: console,
logFormatter(level, args, bindings) {
return level.toUpperCase() + " " + bindings.nodeID + ": " + args.join(" ");
}
});
// External Pino logger
const pino = require("pino")({ level: "info" });
const broker = new ServiceBroker({
logger: bindings => pino.child(bindings)
});
// External Bunyan logger
const logger = require("bunyan").createLogger({ name: "moleculer", level: "info" });
const broker = new ServiceBroker({
logger: bindings => logger.child(bindings)
});
/* *******************************************************************************************
* SERVICE SCHEMA
* ******************************************************************************************* */
module.exports = {
// Name
name: "greeter",
// Version
version: 2,
// Settings
settings: {},
// Metadata
metadata: {},
// Dependencies
dependencies: [],
// Actions
actions: {
// Shorthand actions
hello() {
// Call a method
this.doSomething();
return "Hello Moleculer";
},
// With properties
welcome: {
// Cache options
cache: {
keys: ["name"]
},
// Validation options
params: {
name: "string"
},
// Action handler
handler(ctx) {
return `Welcome, ${ctx.params.name}`;
}
}
},
events: {
"user.created"(payload, sender) {
}
},
// Service methods
methods: {
doSomething() {}
},
// Lifecycle event handlers
created() {
console.log("Service created");
},
started() {
console.log("Service started");
return Promise.resolve();
},
stopped() {
console.log("Service stopped");
return Promise.resolve();
}
};
/* *******************************************************************************************
* SERVICE
* ******************************************************************************************* */
this.name // Name of service
this.version // Version of service
this.settings // Settings of service
this.schema // Schema definition of service
this.broker // Broker instance
this.Promise // Class of Promise (Bluebird)
this.logger // Logger instance
this.actions // Actions of service.
this.waitForServices // Pointer to ‘broker.waitForServices’ method
/* *******************************************************************************************
* CONTEXT
* ******************************************************************************************* */
ctx.id // Context ID
ctx.broker // Broker instance
ctx.action // Action definition
ctx.nodeID // Node ID
ctx.requestID // Request ID
ctx.parentID // ID of parent context (in case of sub-calls).
ctx.params // Request params
ctx.meta // Request metadata
ctx.callerNodeID // Caller Node ID if it is requested from a remote node.
ctx.level // Request level (in case of sub-calls). The first level is 1.
// Make a sub-call
ctx.call(actionName, params, callingOptions)
// Emit an event
ctx.emit(eventName, payload, groups);
================================================
FILE: backend/node.js
================================================
/* *******************************************************************************************
* SYNOPSIS
* http://nodejs.org/api/synopsis.html
* ******************************************************************************************* */
var http = require('http');
// An example of a web server written with Node which responds with 'Hello World'.
// To run the server, put the code into a file called example.js and execute it with the node program.
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
/* *******************************************************************************************
* GLOBAL OBJECTS
* http://nodejs.org/api/globals.html
* ******************************************************************************************* */
// In browsers, the top-level scope is the global scope.
// That means that in browsers if you're in the global scope var something will define a global variable.
// In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.
__filename; // The filename of the code being executed. (absolute path)
__dirname; // The name of the directory that the currently executing script resides in. (absolute path)
module; // A reference to the current module. In particular module.exports is used for defining what a module exports and makes available through require().
exports; // A reference to the module.exports that is shorter to type.
process; // The process object is a global object and can be accessed from anywhere. It is an instance of EventEmitter.
Buffer; // The Buffer class is a global type for dealing with binary data directly.
/* *******************************************************************************************
* CONSOLE
* http://nodejs.org/api/console.html
* ******************************************************************************************* */
console.log([data], [...]); // Prints to stdout with newline.
console.info([data], [...]); // Same as console.log.
console.error([data], [...]); // Same as console.log but prints to stderr.
console.warn([data], [...]); // Same as console.error.
console.dir(obj); // Uses util.inspect on obj and prints resulting string to stdout.
console.time(label); // Mark a time.
console.timeEnd(label); // Finish timer, record output.
console.trace(label); // Print a stack trace to stderr of the current position.
console.assert(expression, [message]); // Same as assert.ok() where if the expression evaluates as false throw an AssertionError with message.
/* *******************************************************************************************
* TIMERS
* http://nodejs.org/api/timers.html
* ******************************************************************************************* */
setTimeout(callback, delay, [arg], [...]); // To schedule execution of a one-time callback after delay milliseconds. Optionally you can also pass arguments to the callback.
clearTimeout(t); // Stop a timer that was previously created with setTimeout().
setInterval(callback, delay, [arg], [...]); // To schedule the repeated execution of callback every delay milliseconds. Optionally you can also pass arguments to the callback.
clearInterval(t); // Stop a timer that was previously created with setInterval().
setImmediate(callback, [arg], [...]); // To schedule the "immediate" execution of callback after I/O events callbacks and before setTimeout and setInterval.
clearImmediate(immediateObject); // Stop a timer that was previously created with setImmediate().
unref(); // Allow you to create a timer that is active but if it is the only item left in the event loop, node won't keep the program running.
ref(); // If you had previously unref()d a timer you can call ref() to explicitly request the timer hold the program open.
/* *******************************************************************************************
* MODULES
* http://nodejs.org/api/modules.html
* ******************************************************************************************* */
var module = require('./module.js'); // Loads the module module.js in the same directory.
module.require('./another_module.js'); // load another_module as if require() was called from the module itself.
module.id; // The identifier for the module. Typically this is the fully resolved filename.
module.filename; // The fully resolved filename to the module.
module.loaded; // Whether or not the module is done loading, or is in the process of loading.
module.parent; // The module that required this one.
module.children; // The module objects required by this one.
exports.area = function (r) {
return Math.PI * r * r;
};
// If you want the root of your module's export to be a function (such as a constructor)
// or if you want to export a complete object in one assignment instead of building it one property at a time,
// assign it to module.exports instead of exports.
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}
/* *******************************************************************************************
* PROCESS
* http://nodejs.org/api/process.html
* ******************************************************************************************* */
process.on('exit', function(code) {}); // Emitted when the process is about to exit
process.on('uncaughtException', function(err) {}); // Emitted when an exception bubbles all the way back to the event loop. (should not be used)
process.stdout; // A writable stream to stdout.
process.stderr; // A writable stream to stderr.
process.stdin; // A readable stream for stdin.
process.argv; // An array containing the command line arguments.
process.env; // An object containing the user environment.
process.execPath; // This is the absolute pathname of the executable that started the process.
process.execArgv; // This is the set of node-specific command line options from the executable that started the process.
process.arch; // What processor architecture you're running on: 'arm', 'ia32', or 'x64'.
process.config; // An Object containing the JavaScript representation of the configure options that were used to compile the current node executable.
process.pid; // The PID of the process.
process.platform; // What platform you're running on: 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'.
process.title; // Getter/setter to set what is displayed in 'ps'.
process.version; // A compiled-in property that exposes NODE_VERSION.
process.versions; // A property exposing version strings of node and its dependencies.
process.abort(); // This causes node to emit an abort. This will cause node to exit and generate a core file.
process.chdir(dir); // Changes the current working directory of the process or throws an exception if that fails.
process.cwd(); // Returns the current working directory of the process.
process.exit([code]); // Ends the process with the specified code. If omitted, exit uses the 'success' code 0.
process.getgid(); // Gets the group identity of the process.
process.setgid(id); // Sets the group identity of the process.
process.getuid(); // Gets the user identity of the process.
process.setuid(id); // Sets the user identity of the process.
process.getgroups(); // Returns an array with the supplementary group IDs.
process.setgroups(grps); // Sets the supplementary group IDs.
process.initgroups(user, extra_grp); // Reads /etc/group and initializes the group access list, using all groups of which the user is a member.
process.kill(pid, [signal]); // Send a signal to a process. pid is the process id and signal is the string describing the signal to send.
process.memoryUsage(); // Returns an object describing the memory usage of the Node process measured in bytes.
process.nextTick(callback); // On the next loop around the event loop call this callback.
process.maxTickDepth; // Callbacks passed to process.nextTick will usually be called at the end of the current flow of execution, and are thus approximately as fast as calling a function synchronously.
process.umask([mask]); // Sets or reads the process's file mode creation mask.
process.uptime(); // Number of seconds Node has been running.
process.hrtime(); // Returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array.
/* *******************************************************************************************
* CHILD PROCESS
* http://nodejs.org/api/child_process.html
* ******************************************************************************************* */
// Node provides a tri-directional popen facility through the child_process module.
// It is possible to stream data through a child's stdin, stdout, and stderr in a fully non-blocking way.
ChildProcess; // Class. ChildProcess is an EventEmitter.
child.stdin; // A Writable Stream that represents the child process's stdin
child.stdout; // A Readable Stream that represents the child process's stdout
child.stderr; // A Readable Stream that represents the child process's stderr.
child.pid; // The PID of the child process
child.connected; // If .connected is false, it is no longer possible to send messages
child.kill([signal]); // Send a signal to the child process
child.send(message, [sendHandle]); // When using child_process.fork() you can write to the child using child.send(message, [sendHandle]) and messages are received by a 'message' event on the child.
child.disconnect(); // Close the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive.
child_process.spawn(command, [args], [options]); // Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.
child_process.exec(command, [options], callback); // Runs a command in a shell and buffers the output.
child_process.execFile(file, [args], [options], [callback]); // Runs a command in a shell and buffers the output.
child_process.fork(modulePath, [args], [options]); // This is a special case of the spawn() functionality for spawning Node processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in.
/* *******************************************************************************************
* UTIL
* http://nodejs.org/api/util.html
* ******************************************************************************************* */
// These functions are in the module 'util'. Use require('util') to access them.
util.format(format, [...]); // Returns a formatted string using the first argument as a printf-like format. (%s, %d, %j)
util.debug(string); // A synchronous output function. Will block the process and output string immediately to stderr.
util.error([...]); // Same as util.debug() except this will output all arguments immediately to stderr.
util.puts([...]); // A synchronous output function. Will block the process and output all arguments to stdout with newlines after each argument.
util.print([...]); // A synchronous output function. Will block the process, cast each argument to a string then output to stdout. (no newlines)
util.log(string); // Output with timestamp on stdout.
util.inspect(object, [opts]); // Return a string representation of object, which is useful for debugging. (options: showHidden, depth, colors, customInspect)
util.isArray(object); // Returns true if the given "object" is an Array. false otherwise.
util.isRegExp(object); // Returns true if the given "object" is a RegExp. false otherwise.
util.isDate(object); // Returns true if the given "object" is a Date. false otherwise.
util.isError(object); // Returns true if the given "object" is an Error. false otherwise.
util.promisify(fn) // Takes a function whose last argument is a callback and returns a version that returns promises.
util.inherits(constructor, superConstructor); // Inherit the prototype methods from one constructor into another.
/* *******************************************************************************************
* EVENTS
* http://nodejs.org/api/events.html
* ******************************************************************************************* */
// All objects which emit events are instances of events.EventEmitter. You can access this module by doing: require("events");
// To access the EventEmitter class, require('events').EventEmitter.
// All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when a listener is removed.
emitter.addListener(event, listener); // Adds a listener to the end of the listeners array for the specified event.
emitter.on(event, listener); // Same as emitter.addListener().
emitter.once(event, listener); // Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.
emitter.removeListener(event, listener); // Remove a listener from the listener array for the specified event.
emitter.removeAllListeners([event]); // Removes all listeners, or those of the specified event.
emitter.setMaxListeners(n); // By default EventEmitters will print a warning if more than 10 listeners are added for a particular event.
emitter.listeners(event); // Returns an array of listeners for the specified event.
emitter.emit(event, [arg1], [arg2], [...]); // Execute each of the listeners in order with the supplied arguments. Returns true if event had listeners, false otherwise.
EventEmitter.listenerCount(emitter, event); // Return the number of listeners for a given event.
/* *******************************************************************************************
* STREAM
* http://nodejs.org/api/stream.html
* ******************************************************************************************* */
// A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is stdout.
// Streams are readable, writable, or both. All streams are instances of EventEmitter.
// The Readable stream interface is the abstraction for a source of data that you are reading from.
// In other words, data comes out of a Readable stream.
// A Readable stream will not start emitting data until you indicate that you are ready to receive it.
// Examples of readable streams include: http responses on the client, http requests on the server, fs read streams
// zlib streams, crypto streams, tcp sockets, child process stdout and stderr, process.stdin.
var readable = getReadableStreamSomehow();
readable.on('readable', function() {}); // When a chunk of data can be read from the stream, it will emit a 'readable' event.
readable.on('data', function(chunk) {}); // If you attach a data event listener, then it will switch the stream into flowing mode, and data will be passed to your handler as soon as it is available.
readable.on('end', function() {}); // This event fires when there will be no more data to read.
readable.on('close', function() {}); // Emitted when the underlying resource (for example, the backing file descriptor) has been closed. Not all streams will emit this.
readable.on('error', function() {}); // Emitted if there was an error receiving data.
// The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.
// This method should only be called in non-flowing mode. In flowing-mode, this method is called automatically until the internal buffer is drained.
readable.read([size]);
readable.setEncoding(encoding); // Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.
readable.resume(); // This method will cause the readable stream to resume emitting data events.
readable.pause(); // This method will cause a stream in flowing-mode to stop emitting data events.
readable.pipe(destination, [options]); // This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
readable.unpipe([destination]); // This method will remove the hooks set up for a previous pipe() call. If the destination is not specified, then all pipes are removed.
readable.unshift(chunk); // This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.
// The Writable stream interface is an abstraction for a destination that you are writing data to.
// Examples of writable streams include: http requests on the client, http responses on the server, fs write streams,
// zlib streams, crypto streams, tcp sockets, child process stdin, process.stdout, process.stderr.
var writer = getWritableStreamSomehow();
writable.write(chunk, [encoding], [callback]); // This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled.
writer.once('drain', write); // If a writable.write(chunk) call returns false, then the drain event will indicate when it is appropriate to begin writing more data to the stream.
writable.end([chunk], [encoding], [callback]); // Call this method when no more data will be written to the stream.
writer.on('finish', function() {}); // When the end() method has been called, and all data has been flushed to the underlying system, this event is emitted.
writer.on('pipe', function(src) {}); // This is emitted whenever the pipe() method is called on a readable stream, adding this writable to its set of destinations.
writer.on('unpipe', function(src) {}); // This is emitted whenever the unpipe() method is called on a readable stream, removing this writable from its set of destinations.
writer.on('error', function(src) {}); // Emitted if there was an error when writing or piping data.
// Duplex streams are streams that implement both the Readable and Writable interfaces. See above for usage.
// Examples of Duplex streams include: tcp sockets, zlib streams, crypto streams.
// Transform streams are Duplex streams where the output is in some way computed from the input. They implement both the Readable and Writable interfaces. See above for usage.
// Examples of Transform streams include: zlib streams, crypto streams.
/* *******************************************************************************************
* FILE SYSTEM
* http://nodejs.org/api/fs.html
* ******************************************************************************************* */
// To use this module do require('fs').
// All the methods have asynchronous and synchronous forms.
fs.rename(oldPath, newPath, callback); // Asynchronous rename. No arguments other than a possible exception are given to the completion callback.Asynchronous ftruncate. No arguments other than a possible exception are given to the completion callback.
fs.renameSync(oldPath, newPath); // Synchronous rename.
fs.ftruncate(fd, len, callback); // Asynchronous ftruncate. No arguments other than a possible exception are given to the completion callback.
fs.ftruncateSync(fd, len); // Synchronous ftruncate.
fs.truncate(path, len, callback); // Asynchronous truncate. No arguments other than a possible exception are given to the completion callback.
fs.truncateSync(path, len); // Synchronous truncate.
fs.chown(path, uid, gid, callback); // Asynchronous chown. No arguments other than a possible exception are given to the completion callback.
fs.chownSync(path, uid, gid); // Synchronous chown.
fs.fchown(fd, uid, gid, callback); // Asynchronous fchown. No arguments other than a possible exception are given to the completion callback.
fs.fchownSync(fd, uid, gid); // Synchronous fchown.
fs.lchown(path, uid, gid, callback); // Asynchronous lchown. No arguments other than a possible exception are given to the completion callback.
fs.lchownSync(path, uid, gid); // Synchronous lchown.
fs.chmod(path, mode, callback); // Asynchronous chmod. No arguments other than a possible exception are given to the completion callback.
fs.chmodSync(path, mode); // Synchronous chmod.
fs.fchmod(fd, mode, callback); // Asynchronous fchmod. No arguments other than a possible exception are given to the completion callback.
fs.fchmodSync(fd, mode); // Synchronous fchmod.
fs.lchmod(path, mode, callback); // Asynchronous lchmod. No arguments other than a possible exception are given to the completion callback.
fs.lchmodSync(path, mode); // Synchronous lchmod.
fs.stat(path, callback); // Asynchronous stat. The callback gets two arguments (err, stats) where stats is a fs.Stats object.
fs.statSync(path); // Synchronous stat. Returns an instance of fs.Stats.
fs.lstat(path, callback); // Asynchronous lstat. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
fs.lstatSync(path); // Synchronous lstat. Returns an instance of fs.Stats.
fs.fstat(fd, callback); // Asynchronous fstat. The callback gets two arguments (err, stats) where stats is a fs.Stats object. fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.
fs.fstatSync(fd); // Synchronous fstat. Returns an instance of fs.Stats.
fs.link(srcpath, dstpath, callback); // Asynchronous link. No arguments other than a possible exception are given to the completion callback.
fs.linkSync(srcpath, dstpath); // Synchronous link.
fs.symlink(srcpath, dstpath, [type], callback); // Asynchronous symlink. No arguments other than a possible exception are given to the completion callback. The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other platforms)
fs.symlinkSync(srcpath, dstpath, [type]); // Synchronous symlink.
fs.readlink(path, callback); // Asynchronous readlink. The callback gets two arguments (err, linkString).
fs.readlinkSync(path); // Synchronous readlink. Returns the symbolic link's string value.
fs.unlink(path, callback); // Asynchronous unlink. No arguments other than a possible exception are given to the completion callback.
fs.unlinkSync(path); // Synchronous unlink.
fs.realpath(path, [cache], callback); // Asynchronous realpath. The callback gets two arguments (err, resolvedPath).
fs.realpathSync(path, [cache]); // Synchronous realpath. Returns the resolved path.
fs.rmdir(path, callback); // Asynchronous rmdir. No arguments other than a possible exception are given to the completion callback.
fs.rmdirSync(path); // Synchronous rmdir.
fs.mkdir(path, [mode], callback); // Asynchronous mkdir. No arguments other than a possible exception are given to the completion callback. mode defaults to 0777.
fs.mkdirSync(path, [mode]); // Synchronous mkdir.
fs.readdir(path, callback); // Asynchronous readdir. Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.
fs.readdirSync(path); // Synchronous readdir. Returns an array of filenames excluding '.' and '..'.
fs.close(fd, callback); // Asynchronous close. No arguments other than a possible exception are given to the completion callback.
fs.closeSync(fd); // Synchronous close.
fs.open(path, flags, [mode], callback); // Asynchronous file open.
fs.openSync(path, flags, [mode]); // Synchronous version of fs.open().
fs.utimes(path, atime, mtime, callback); // Change file timestamps of the file referenced by the supplied path.
fs.utimesSync(path, atime, mtime); // Synchronous version of fs.utimes().
fs.futimes(fd, atime, mtime, callback); // Change the file timestamps of a file referenced by the supplied file descriptor.
fs.futimesSync(fd, atime, mtime); // Synchronous version of fs.futimes().
fs.fsync(fd, callback); // Asynchronous fsync. No arguments other than a possible exception are given to the completion callback.
fs.fsyncSync(fd); // Synchronous fsync.
fs.write(fd, buffer, offset, length, position, callback); // Write buffer to the file specified by fd.
fs.writeSync(fd, buffer, offset, length, position); // Synchronous version of fs.write(). Returns the number of bytes written.
fs.read(fd, buffer, offset, length, position, callback); // Read data from the file specified by fd.
fs.readSync(fd, buffer, offset, length, position); // Synchronous version of fs.read. Returns the number of bytesRead.
fs.readFile(filename, [options], callback); // Asynchronously reads the entire contents of a file.
fs.readFileSync(filename, [options]); // Synchronous version of fs.readFile. Returns the contents of the filename. If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
fs.writeFile(filename, data, [options], callback); // Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.
fs.writeFileSync(filename, data, [options]); // The synchronous version of fs.writeFile.
fs.appendFile(filename, data, [options], callback); // Asynchronously append data to a file, creating the file if it not yet exists. data can be a string or a buffer.
fs.appendFileSync(filename, data, [options]); // The synchronous version of fs.appendFile.
fs.watch(filename, [options], [listener]); // Watch for changes on filename, where filename is either a file or a directory. The returned object is a fs.FSWatcher. The listener callback gets two arguments (event, filename). event is either 'rename' or 'change', and filename is the name of the file which triggered the event.
fs.exists(path, callback); // Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false. (should not be used)
fs.existsSync(path); // Synchronous version of fs.exists. (should not be used)
// fs.Stats: objects returned from fs.stat(), fs.lstat() and fs.fstat() and their synchronous counterparts are of this type.
stats.isFile();
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() // (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()
fs.createReadStream(path, [options]); // Returns a new ReadStream object.
fs.createWriteStream(path, [options]); // Returns a new WriteStream object.
/* *******************************************************************************************
* PATH
* http://nodejs.org/api/fs.html
* ******************************************************************************************* */
// Use require('path') to use this module.
// This module contains utilities for handling and transforming file paths.
// Almost all these methods perform only string transformations.
// The file system is not consulted to check whether paths are valid.
path.normalize(p); // Normalize a string path, taking care of '..' and '.' parts.
path.join([path1], [path2], [...]); // Join all arguments together and normalize the resulting path.
path.resolve([from ...], to); // Resolves 'to' to an absolute path.
path.relative(from, to); // Solve the relative path from 'from' to 'to'.
path.dirname(p); // Return the directory name of a path. Similar to the Unix dirname command.
path.basename(p, [ext]); // Return the last portion of a path. Similar to the Unix basename command.
path.extname(p); // Return the extension of the path, from the last '.' to end of string in the last portion of the path.
path.sep; // The platform-specific file separator. '\\' or '/'.
path.delimiter; // The platform-specific path delimiter, ';' or ':'.
/* *******************************************************************************************
* HTTP
* http://nodejs.org/api/http.html
* ******************************************************************************************* */
// To use the HTTP server and client one must require('http').
http.STATUS_CODES; // A collection of all the standard HTTP response status codes, and the short description of each.
http.request(options, [callback]); // This function allows one to transparently issue requests.
http.get(options, [callback]); // Set the method to GET and calls req.end() automatically.
server = http.createServer([requestListener]); // Returns a new web server object. The requestListener is a function which is automatically added to the 'request' event.
server.listen(port, [hostname], [backlog], [callback]); // Begin accepting connections on the specified port and hostname.
server.listen(path, [callback]); // Start a UNIX socket server listening for connections on the given path.
server.listen(handle, [callback]); // The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: } object.
server.close([callback]); // Stops the server from accepting new connections.
server.setTimeout(msecs, callback); // Sets the timeout value for sockets, and emits a 'timeout' event on the Server object, passing the socket as an argument, if a timeout occurs.
server.maxHeadersCount; // Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - no limit will be applied.
server.timeout; // The number of milliseconds of inactivity before a socket is presumed to have timed out.
server.on('request', function (request, response) { }); // Emitted each time there is a request.
server.on('connection', function (socket) { }); // When a new TCP stream is established.
server.on('close', function () { }); // Emitted when the server closes.
server.on('checkContinue', function (request, response) { }); // Emitted each time a request with an http Expect: 100-continue is received.
server.on('connect', function (request, socket, head) { }); // Emitted each time a client requests a http CONNECT method.
server.on('upgrade', function (request, socket, head) { }); // Emitted each time a client requests a http upgrade.
server.on('clientError', function (exception, socket) { }); // If a client connection emits an 'error' event - it will forwarded here.
request.write(chunk, [encoding]); // Sends a chunk of the body.
request.end([data], [encoding]); // Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream.
request.abort(); // Aborts a request.
request.setTimeout(timeout, [callback]); // Once a socket is assigned to this request and is connected socket.setTimeout() will be called.
request.setNoDelay([noDelay]); // Once a socket is assigned to this request and is connected socket.setNoDelay() will be called.
request.setSocketKeepAlive([enable], [initialDelay]); // Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called.
request.on('response', function(response) { }); // Emitted when a response is received to this request. This event is emitted only once.
request.on('socket', function(socket) { }); // Emitted after a socket is assigned to this request.
request.on('connect', function(response, socket, head) { }); // Emitted each time a server responds to a request with a CONNECT method. If this event isn't being listened for, clients receiving a CONNECT method will have their connections closed.
request.on('upgrade', function(response, socket, head) { }); // Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.
request.on('continue', function() { }); // Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.
response.write(chunk, [encoding]); // This sends a chunk of the response body. If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.
response.writeContinue(); // Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent.
response.writeHead(statusCode, [reasonPhrase], [headers]); // Sends a response header to the request.
response.setTimeout(msecs, callback); // Sets the Socket's timeout value to msecs. If a callback is provided, then it is added as a listener on the 'timeout' event on the response object.
response.setHeader(name, value); // Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.
response.getHeader(name); // Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive.
response.removeHeader(name); // Removes a header that's queued for implicit sending.
response.addTrailers(headers); // This method adds HTTP trailing headers (a header but at the end of the message) to the response.
response.end([data], [encoding]); // This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.
response.statusCode; // When using implicit headers (not calling response.writeHead() explicitly), this property controls the status code that will be sent to the client when the headers get flushed.
response.headersSent; // Boolean (read-only). True if headers were sent, false otherwise.
response.sendDate; // When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.
response.on('close', function () { }); // Indicates that the underlying connection was terminated before response.end() was called or able to flush.
response.on('finish', function() { }); // Emitted when the response has been sent.
message.httpVersion; // In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server.
message.headers; // The request/response headers object.
message.trailers; // The request/response trailers object. Only populated after the 'end' event.
message.method; // The request method as a string. Read only. Example: 'GET', 'DELETE'.
message.url; // Request URL string. This contains only the URL that is present in the actual HTTP request.
message.statusCode; // The 3-digit HTTP response status code. E.G. 404.
message.socket; // The net.Socket object associated with the connection.
message.setTimeout(msecs, callback); // Calls message.connection.setTimeout(msecs, callback).
/* *******************************************************************************************
* URL
* http://nodejs.org/api/url.html
* ******************************************************************************************* */
// This module has utilities for URL resolution and parsing. Call require('url') to use it.
url.parse(urlStr, [parseQueryString], [slashesDenoteHost]); // Take a URL string, and return an object.
url.format(urlObj); // Take a parsed URL object, and return a formatted URL string.
url.resolve(from, to); // Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.
/* *******************************************************************************************
* QUERY STRING
* http://nodejs.org/api/querystring.html
* ******************************************************************************************* */
// This module provides utilities for dealing with query strings. Call require('querystring') to use it.
querystring.stringify(obj, [sep], [eq]); // Serialize an object to a query string. Optionally override the default separator ('&') and assignment ('=') characters.
querystring.parse(str, [sep], [eq], [options]); // Deserialize a query string to an object. Optionally override the default separator ('&') and assignment ('=') characters.
/* *******************************************************************************************
* ASSERT
* http://nodejs.org/api/assert.html
* ******************************************************************************************* */
// This module is used for writing unit tests for your applications, you can access it with require('assert').
assert.fail(actual, expected, message, operator); // Throws an exception that displays the values for actual and expected separated by the provided operator.
assert(value, message); assert.ok(value, [message]); // Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);
assert.equal(actual, expected, [message]); // Tests shallow, coercive equality with the equal comparison operator ( == ).
assert.notEqual(actual, expected, [message]); // Tests shallow, coercive non-equality with the not equal comparison operator ( != ).
assert.deepEqual(actual, expected, [message]); // Tests for deep equality.
assert.notDeepEqual(actual, expected, [message]); // Tests for any deep inequality.
assert.strictEqual(actual, expected, [message]); // Tests strict equality, as determined by the strict equality operator ( === )
assert.notStrictEqual(actual, expected, [message]); // Tests strict non-equality, as determined by the strict not equal operator ( !== )
assert.throws(block, [error], [message]); // Expects block to throw an error. error can be constructor, RegExp or validation function.
assert.doesNotThrow(block, [message]); // Expects block not to throw an error, see assert.throws for details.
assert.ifError(value); // Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.
/* *******************************************************************************************
* OS
* http://nodejs.org/api/os.html
* ******************************************************************************************* */
// Provides a few basic operating-system related utility functions.
// Use require('os') to access this module.
os.tmpdir(); // Returns the operating system's default directory for temp files.
os.endianness(); // Returns the endianness of the CPU. Possible values are "BE" or "LE".
os.hostname(); // Returns the hostname of the operating system.
os.type(); // Returns the operating system name.
os.platform(); // Returns the operating system platform.
os.arch(); // Returns the operating system CPU architecture.
os.release(); // Returns the operating system release.
os.uptime(); // Returns the system uptime in seconds.
os.loadavg(); // Returns an array containing the 1, 5, and 15 minute load averages.
os.totalmem(); // Returns the total amount of system memory in bytes.
os.freemem(); // Returns the amount of free system memory in bytes.
os.cpus(); // Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of milliseconds the CPU/core spent in: user, nice, sys, idle, and irq).
os.networkInterfaces(); // Get a list of network interfaces.
os.EOL; // A constant defining the appropriate End-of-line marker for the operating system.
/* *******************************************************************************************
* BUFFER
* http://nodejs.org/api/buffer.html
* ******************************************************************************************* */
// Buffer is used to dealing with binary data
// Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap
Buffer.from(size); // Allocates a new buffer of size octets.
Buffer.from(array); // Allocates a new buffer using an array of octets.
Buffer.from(str, [encoding]); // Allocates a new buffer containing the given str. encoding defaults to 'utf8'.
Buffer.isEncoding(encoding); // Returns true if the encoding is a valid encoding argument, or false otherwise.
Buffer.isBuffer(obj); // Tests if obj is a Buffer
Buffer.concat(list, [totalLength]); // Returns a buffer which is the result of concatenating all the buffers in the list together.
Buffer.byteLength(string, [encoding]); // Gives the actual byte length of a string.
buf.write(string, [offset], [length], [encoding]); // Writes string to the buffer at offset using the given encoding
buf.toString([encoding], [start], [end]); // Decodes and returns a string from buffer data encoded with encoding (defaults to 'utf8') beginning at start (defaults to 0) and ending at end (defaults to buffer.length).
buf.toJSON(); // Returns a JSON-representation of the Buffer instance, which is identical to the output for JSON Arrays
buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd]); // Does copy between buffers. The source and target regions can be overlapped
buf.slice([start], [end]); // Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer.
buf.fill(value, [offset], [end]); // Fills the buffer with the specified value
buf[index]; // Get and set the octet at index
buf.length; // The size of the buffer in bytes, Note that this is not necessarily the size of the contents
buffer.INSPECT_MAX_BYTES; // How many bytes will be returned when buffer.inspect() is called. This can be overridden by user modules.
================================================
FILE: backend/sails.js
================================================
/********************************************************************************************
* SAILS.JS CHEATSHEET
* REFERENCE: https://sailsjs.com/documentation/reference
* CONCEPTS: https://sailsjs.com/documentation/concepts
* APP STRUCTURE: https://sailsjs.com/documentation/anatomy
*
* 1. APPLICATION
* 2. BLUEPRINT API
* 3. COMMAND-LINE INTERFACE
* 4. CONFIGURATION
* 5. REQUEST
* 6. RESPONSE
* 7. WATERLINE ORM
* 8. WEBSOCKETS
********************************************************************************************/
/********************************************************************************************
* 1. APPLICATION
* https://sailsjs.com/documentation/reference/application
********************************************************************************************/
// A dictionary of all loaded Sails models, indexed by their identity.
sails.models
// A dictionary of all accessible helpers, including organics.
sails.helpers
// A dictionary of all loaded Sails hooks, indexed by their identity.
sails.hooks
// The full set of configuration options for the Sails instance
// It is assembled automatically when Sails loads your app
// merging together command-line arguments, environment variables, your .sailsrc file,
// and the configuration objects exported from any and all modules in your app's config/ directory.
sails.config
// The runtime values of your app's custom configuration settings.
sails.config.custom
// A set of convenience methods for low - level interaction with connected websockets.
sails.sockets
// Talk to Socket.io directly.
sails.io
// A regular expression designed for use in identifying URL paths that seem like they are probably
// for a static asset of some kind (e.g. image, stylesheet, favicon.ico, robots.txt, etc).
sails.LOOKS_LIKE_ASSET_RX
// Return a dictionary of Sails actions.
sails.getActions()
// Look up the first route pointing at the specified target (e.g. MeController.login)
// and return a dictionary containing its method and URL.
sails.getRouteFor(target)
// Look up the first route pointing at the specified target (e.g. entrance/view-login)
// and return its URL.
sails.getUrlFor(target)
// Lift a Sails app programmatically.
// This does exactly what you might be used to seeing by now when you run sails lift.
sailsApp.lift(configOverrides, function(err) {})
// Load a Sails app into memory-- but without lifting an HTTP server.
// Useful for writing tests, command - line scripts, and scheduled jobs.
sailsApp.load(configOverrides, function(err) {})
// Shut down a lifted Sails app and have it cease listening for / responding to any future requests.
sails.lower(callback)
// Register a new Sails action that can then be bound to a route.
sails.registerAction(action, name)
// Register a new action middleware function that will be applied to actions
// with the specified identities.
sails.registerActionMiddleware(actionMiddlewareFns, actionIdentities)
// Flush and reload all Sails actions.
sails.reloadActions()
// Compile a view into an HTML template.
sails.renderView(pathToView, templateData)
// Make a virtual request to a running Sails instance.
sails.request(request)
sails.request(url, body)
sails.request(url, callback)
sails.request(url, body, callback)
// Access a particular datastore, or the default datastore.
sails.getDatastore(datastoreName)
// Log a message or some data at the "debug" log level using Sails' built-in logger.
sails.log(message)
/********************************************************************************************
* 2. BLUEPRINT API
* https://sailsjs.com/documentation/reference/blueprint-api
********************************************************************************************/
// Find a list of records that match the specified criteria
// and (if possible) subscribe to each of them.
GET /:model
// Look up the record with the specified id from the database
// and (if possible) subscribe to the record to hear about any future changes.
GET /:model/:id
// Populate and return foreign record(s) for the given association of this record.
GET /:model/:id/:association
// Create a new record in your database
// and notify subscribed sockets that a newly record is created
POST /:model
// Update an existing record in the database
// and notify subscribed sockets that it has changed.
PATCH /:model/:id
// Replace all of the foreign records in one of this record's collections
// and notify subscribed sockets to the parent record.
PUT /:model/:id/:association
// Add a foreign record to one of this record's collections
// and notify subscribed sockets to the parent record.
PUT /:model/:id/:association/:fk
// Delete the record specified by id from the database forever
// and notify subscribed sockets that a record has been deleted
DELETE /:model/:id
// Remove a foreign record from one of this record's collections
// and notify subscribed sockets about this removed child
DELETE /:model/:id/:association/:fk
/********************************************************************************************
* 3. COMMAND-LINE INTERFACE
* https://sailsjs.com/documentation/reference/command-line-interface
********************************************************************************************/
// Lift your Node.js/Sails.js app in interactive mode, and enter the REPL.
// Useful for trying out Waterline queries, quickly managing your data, and checking
// out your project's runtime configuration.
sails console [--dontLift]
// Generate api/models/Foo.js, including attributes with the specified types if provided.
sails generate model
// Generate a standalone action.
sails generate action
// Generate a helper at api/helpers/foo.js.
sails generate helper
// Generate api/controllers/FooController.js, including actions with the specified names if provided.
sails generate controller
// Generate a project hook in api/hooks/foo/.
sails generate hook
// Generate a foo folder containing the files necessary for building a new generator.
sails generate generator
// Generate a custom response at api/responses/foo.js
sails generate response
// Generate a api/adapters/foo/ folder containing the files necessary for building a new adapter.
sails generate adapter
// Generate a sails.io.js file at the specified location, overwriting the default sails.io.js if applicable.
sails generate sails.io.js
// Generate api/models/Foo.js and api/controllers/FooController.js.
sails generate api
// Alias for sails new.
sails generate new
// Experimental. Adds the following files to your app:
// .gitignore, .jshintrc, .editorconfig, .npmignore, .travis.yml, .appveyor.yml
sails generate etc
// Attach the node debugger and lift the sails app; similar to running node--inspect app.js.
// You can then use a tool like the Chrome DevTools to interactively debug your apps.
sails inspect
// Run the Sails app in the current dir
// (if node_modules/sails exists, it will be used instead of the globally installed Sails)
sails lift [--prod] [--port ] [--verbose] [--silly]
// Create a new sails project.
sails new [--no-frontend] [--minimal] [--without=package,package,package]
// Get the version of your computer's globally installed Sails command-line tool
// (i.e. the version you installed with npm install -g sails).
sails version
/********************************************************************************************
* 4. CONFIGURATION
* https://sailsjs.com/documentation/reference/configuration
********************************************************************************************/
// Determines which TCP port your Sails app will use to listen for incoming requests.
sails.config.port
// Declare the host name of your Sails app (By default, Sails will assume localhost).
sails.config.explicitHost
// The runtime “environment” of your Sails app (usually either development or production).
sails.config.environment
// A time limit, in milliseconds, imposed on all hooks in your app (default to 20000)
sails.config.hookTimeout
// Configure SSL settings for HTTPs and WSS
sails.config.ssl
// These configurable settings allow you to configure the blueprint API in Sails.
sails.config.blueprints
// Asynchronous bootstrap function that runs before your Sails app gets lifted (i.e. starts up).
// Can be used for setting up baseline data, running sanity checks on the status of your database...
sails.config.bootstrap
// Custom configuration for your app (one-off settings specific to your application)
// Things like the domain to use when sending emails, or 3rd party API keys for Stripe, Mailgun...
sails.config.custom
// Datastore configurations(or simply datastores) are like "saved settings" for your adapters.
sails.config.datastores
// Configuration for the global variables that Sails exposes by default.
sails.config.globals
// Configuration for your app's underlying HTTP server.
sails.config.http
// Configuration for Sails' built-in internationalization & localization features.
sails.config.i18n
// Configuration for the logger in your Sails app.
sails.config.log
// Your default project-wide model settings.
sails.config.models
// Dictionary that maps policies to an app’s actions.
sails.config.policies
// Configuration for custom (aka "explicit") routes.
sails.config.routes
// Configuration for your app's security settings.
sails.config.security
// Configuration for Sails's built-in session support.
sails.config.session
// Provide transparent access to Socket.io
sails.config.sockets
// Configuration for your app's server-side views.
sails.config.views
/********************************************************************************************
* 5. REQUEST
* https://sailsjs.com/documentation/reference/request-req
********************************************************************************************/
// The moment that Sails started processing the request, as a Javascript Date object.
req._startTime
// An object containing text parameters from the parsed request body, defaulting to {}.
// If a request contains one or more file uploads, only the text parameters sent before
// the first file parameter will be available in req.body.
req.body
// An object containing all of the unsigned cookies from this request (req).
req.cookies
// A flag indicating the user-agent sending this request (req) wants "fresh" data
// (as indicated by the "if-none-match", "cache-control", and/or "if-modified-since" request headers.)
req.fresh
// An object containing pre-defined/custom header given in the current request.
req.headers
// Returns the hostname supplied in the host HTTP header.
// This header may be set either by the client or by the proxy.
req.hostname
// The IP address of the client who sent this request (req).
req.ip
// Contains the IP addresses in this request's "X-Forwarded-For" header
// as an array of the IP address strings.
req.ips
// A flag indicating whether or not this request (req) originated from a Socket.io connection.
req.isSocket
// The request method (aka "verb".)
// All requests to a Sails server have a "method", even via WebSockets.
req.method
// Dictionary (plain JavaScript object) of request-agnostic settings available in your app's actions.
req.options
// Retains the original request URL allowing you to rewrite req.url freely for internal routing purposes.
// In almost all cases, you’ll want to use req.url instead.
req.originalUrl
// An object containing parameter values parsed from the URL path.
req.params
// The URL pathname from the request URL string of the current request (req).
req.path
// The protocol used to send this request (req).
req.protocol
// A dictionary containing the parsed query-string, defaulting to {}.
req.query
// Indicates whether or not the request was sent over a secure TLS connection (i.e. https:// or wss://).
req.secure
// A dictionary containing all of the signed cookies from this request (req).
req.signedCookies
// If the current Request (req) originated from a connected Socket.io client,
// req.socket refers to the raw Socket.io socket instance.
req.socket
// An array of all the subdomains in this request's URL.
req.subdomains
// Like req.path, but also includes the query string suffix.
req.url
// A flag indicating whether the requesting client would prefer a JSON response
// (as opposed to some other format, like XML or HTML.)
req.wantsJSON
// A flag indicating whether the current request (req) appears to be an AJAX request.
req.xhr
// Return whether this request (req) advertises that it understands the specified media type.
req.accepts(mediaType)
// Return whether this request (req) advertises that it is able to handle any of the specified
// character set(s), and if so, which one.
req.acceptsCharsets(charset1, charset2, …)
// Return whether this request (req) advertises that it understands any of the specified
// language(s), and if so, which one.
req.acceptsLanguages(language1, language2, …)
// Returns the value of all parameters sent in the request, merged together into a single dictionary
req.allParams()
// Build and return a Skipper Upstream representing an incoming multipart file upload from the specified field.
req.file(field)
// Returns the value of the specified header field in this request (req). Note that header names are case-insensitive.
req.get(header)
// Returns true if this request's declared "Content-Type" matches the specified media/mime type.
req.is(type)
// Returns the value of the parameter with the specified name.
req.param(name[, defaultValue])
// Override the inferred locale for this request.
req.setLocale(override)
// Time out this request if a response is not sent within the specified number of milliseconds.
req.setTimeout(numMilliseconds)
/********************************************************************************************
* 6. RESPONSE
* https://sailsjs.com/documentation/reference/response-res
********************************************************************************************/
// Indicate to a web browser or other user agent that an outgoing file download sent
// in this response should be "Saved as..." rather than "Opened", and optionally specify the
// name for the newly downloaded file on disk.
res.attachment([filename])
// This method is used to send a 200 ("OK") response back down to the client.
res.ok(data)
// This method is used to send a 400 ("Bad Request") response back down
// to the client indicating that the request is invalid.
res.badRequest(data)
// This method is used to send a 403 ("Forbidden") response back down
// to the client indicating that the request is not allowed.
res.forbidden()
// This method is used to send a 404 ("Not Found") response using either res.json() or res.view().
res.notFound()
// This method is used to send a 500 ("Server Error") response back down to the client indicating
// that some kind of server error occurred (i.e. the error is not the requesting user agent's fault).
res.serverError(err)
res.serverError()
// Sets a cookie with name (name) and value (value) to be sent along with the response.
res.cookie(name, value[, options])
// Clears cookie (name) in the response.
res.clearCookie(name[, options])
// Returns the current value of the specified response header (header).
res.get(header)
// Sets specified response header (header) to the specified value (value).
res.set(header, value)
res.set(headers)
// Sends a JSON response composed of a stringified version of the specified data.
res.json([statusCode,] data)
// Send a JSON or JSONP response.
res.jsonp()
// Sets the "Location" response header to the specified URL expression(url).
res.location(url)
// Redirect the requesting user-agent to the given absolute or relative url.
res.redirect(url)
res.redirect(statusCode, url)
// Send a string response in a format other than JSON (XML, CSV, plain text, etc.
// If you want to send a dictionary or JSON, use res.json().
// If you want to send a custom status code, call req.status() first.
res.send([string])
// Set the status code of this response.
res.status(statusCode)
// Sets the "Content-Type" response header to the specified type.
res.type(type)
// Respond with an HTML page.
res.view(pathToView, locals)
res.view(pathToView)
res.view(locals)
res.view()
/********************************************************************************************
* 7. WATERLINE ORM
* https://sailsjs.com/documentation/reference/waterline-orm
********************************************************************************************/
// --> DATASTORE <--
// Return the default datastore
var datastore = sails.getDatastore()
// The generic, stateless, low-level driver for this datastore (if the adapter supports it).
datastore.driver
// The live connection manager for this datastore.
datastore.manager
// Lease a new connection from the datastore for use in running multiple queries
// on the same connection (i.e. so that the logic provided in during can reuse the db connection).
await datastore.leaseConnection(during)
// Execute a raw SQL query using this datastore.
await datastore.sendNativeQuery(sql, valuesToEscape)
// Fetch a preconfigured deferred object hooked up to the sails-mysql or sails-postgresql adapter
// (and consequently the appropriate driver)
await datastore.transaction(during)
// --> MODELS <--
// Add one or more existing child records to the specified collection.
MyModel.addToCollection(parentId, association).members(childIds)
// Remove one or more members from the specified collection
MyModel.removeFromCollection()
// Replace all members of the specified collection
MyModel.replaceCollection()
// Archive ("soft-delete") records that match the specified criteria,
// saving them as new records in the built-in Archive model, then destroying the originals.
MyModel.archive(criteria)
// Archive ("soft-delete") the record that matches the specified criteria,
// saving it (if it exists) as a new record in the built-in Archive model, then destroying the original.
MyModel.archiveOne(criteria);
// Get the total number of records matching the specified criteria.
MyModel.count(criteria)
// Get the aggregate mean of the specified attribute across all matching records.
MyModel.avg(numericAttrName, criteria)
// Get the aggregate sum of the specified attribute across all matching records.
MyModel.sum(numericAttrName, criteria)
// Find records in your database that match the given criteria.
MyModel.find(criteria)
// Attempt to find a particular record in your database that matches the given criteria.
MyModel.findOne(criteria)
// Find the record matching the specified criteria.
// If no such record exists, create one using the provided initial values.
MyModel.findOrCreate(criteria, initialValues)
// Create a record in the database.
MyModel.create(initialValues)
MyModel.create(initialValues).fetch() // Created record will be returned
// Create a set of records in the database.
MyModel.createEach(initialValues)
MyModel.createEach(initialValues).fetch() // Created records will be returned
// Update all records matching criteria.
MyModel.update(criteria, valuesToSet)
MyModel.update(criteria, valuesToSet).fetch() // Updated records will be returned
// Update the record that matches the given criteria, if one exists.
MyModel.updateOne(criteria).set(valuesToSet);
// Destroy records in your database that match the given criteria.
MyModel.destroy(criteria)
MyModel.destroy(criteria).fetch() // Destroyed record will be returned
// Destroy the record in your database that matches the given criteria, if one exists.
MyModel.destroyOne(criteria);
// Access the datastore for a particular model.
MyModel.getDatastore()
// Stream records from your database one at a time or in batches,
// without first having to buffer the entire result set in memory.
MyModel.stream(criteria)
// Verify that a value would be valid for a given attribute, then return it, loosely coerced.
MyModel.validate(attrName, value)
// --> QUERIES <--
// Set the maximum number of records to retrieve when executing a query instance.
query.limit(maximum)
// Indicate a number of records to skip before returning the results from executing a query instance.
query.skip(numRecordsToSkip)
// Set the order in which retrieved records should be returned when executing a query instance.
query.sort(sortClause)
// Specify a where clause for filtering a query.
query.where(whereClause)
// Tell Waterline (and the underlying database adapter) to send back records that were
// updated/destroyed/created when performing an .update(), .create(), .createEach() or .destroy()
// query. Otherwise, no data will be returned (or if you are using callbacks, the second argument
// to the .exec() callback will be undefined.)
// This is just a shortcut for .meta({fetch: true})
// Warning: This is not recommended for update/destroy queries that affect large numbers of records.
query.fetch()
// Modify a query instance so that, when executed, it will populate child records for the
// specified collection, optionally filtering by subcriteria. Populate may be called more than
// once on the same query, as long as each call is for a different association.
query.populate()
// Decrypt any auto-encrypted attributes in the records returned for this particular query.
// This is just a shortcut for .meta({decrypt: true})
query.decrypt()
// Execute a Waterline query instance.
query.exec(function (err, result) {})
// Begin executing a Waterline query instance and return a promise.
// This is an alternative to .exec().
query.toPromise()
// Capture and intercept the specified error, automatically modifying and re-throwing it,
// or specifying a new Error to be thrown instead. (Still throws.)
query.intercept(filter, handler)
query.intercept(handler)
// Provide additional options to Waterline when executing a query instance.
query.meta(options)
// Execute a Waterline query instance using promises.
// Whenever possible, it is recommended that you use await instead of calling this method.
// This is an alternative to .exec(). When combined with .catch(), it provides the same functionality.
query.then(callback)
// Execute a Waterline query instance using promises.
// Whenever possible, it is recommended that you use await instead of calling this method.
// This is an alternative to .exec(). When combined with .then(), it provides the same functionality.
query.catch(callback)
// Tolerate (swallow) the specified error, and return a new result value (or undefined) instead. (Don't throw.)
query.tolerate(filter, handler)
query.tolerate(filter)
query.tolerate(handler)
// Specify an existing database connection to use for this query.
query.usingConnection(connection)
/********************************************************************************************
* 8. WEB SOCKETS
* https://sailsjs.com/documentation/reference/web-sockets
********************************************************************************************/
// --> RESOURCEFUL PUBSUB (HIGHER LEVEL ABSTRACTION WHICH ARE USED BY SAILS BLUEPRINT API) <--
// Retrieve the name of the PubSub “room” for a given record.
MyModel.getRoomName(id)
// Broadcast an arbitrary message to socket clients subscribed to one or more of this model's records.
// Be sure and check req.isSocket === true before passing in req to refer to the requesting socket.
// If used, the provided req must be from a socket request, not just any old HTTP request.
// Is like sails.sockets.broadcast()
MyModel.publish(ids, data, req)
// Subscribe the requesting client socket to changes/deletions of one or more database records.
// Is like sails.sockets.join()
MyModel.subscribe(req, ids)
// Unsubscribe the requesting client socket from one or more database records.
// Is like sails.sockets.leave()
MyModel.unsubscribe(req, ids)
// --> SAILS.SOCKETS <--
// Subscribe all members of a room to one or more additional rooms.
// In a multi-server environment, the callback function (cb) will be executed when the
// .addRoomMembersToRooms() call completes on the current server. This does not guarantee that
// other servers in the cluster have already finished running the operation.
sails.sockets.addRoomMembersToRooms(sourceRoom, destRooms, cb)
// Broadcast a message to all sockets connected to the server (or any server in the cluster,
// if you have a multi-server deployment using Redis).
sails.sockets.blast(data)
sails.sockets.blast(eventName, data)
sails.sockets.blast(data, socketToOmit)
sails.sockets.blast(eventName, data, socketToOmit)
// Broadcast a message to all sockets in a room (or to a particular socket).
sails.sockets.broadcast(roomNames, data)
sails.sockets.broadcast(roomNames, eventName, data)
sails.sockets.broadcast(roomNames, data, socketToOmit)
sails.sockets.broadcast(roomNames, eventName, data, socketToOmit)
// Parse the socket ID from an incoming socket request (req).
sails.sockets.getId(req)
// Subscribe a socket to a room.
sails.sockets.join(socket, roomName)
sails.sockets.join(socket, roomName, cb)
// Unsubscribe a socket from a room.
sails.sockets.leave(socket, roomName)
sails.sockets.leave(socket, roomName, cb)
// Unsubscribe all members of a room (e.g. chatroom7) from that room and every other room
// they are currently subscribed to; except the automatic room associated with their socket ID.
sails.sockets.leaveAll(roomName, cb)
// Unsubscribe all members of a room from one or more other rooms.
sails.sockets.removeRoomMembersFromRooms(sourceRoom, destRooms, cb)
// --> SOCKET CLIENT <--
// Home of global configuration options for the sails.io.js library, as well as any sockets it creates.
io.sails
// Wait one cycle of the event loop after loading and then attempt to create a new SailsSocket
// and connect it to the URL specified by io.sails.url.
io.sails.autoConnect
// Sockets will automatically (and continuously) attempt to reconnect to the server
// if they become disconnected unexpectedly.
io.sails.reconnection
// Dictionary of headers to be sent by default with every request from this socket.
// Can be overridden via the headers option in .request().
io.sails.headers
// Set an environment for sails.io.js, which affects how much information is logged to the console.
// Valid values are development (full logs) and production (minimal logs).
io.sails.environment
// The URL that the socket is connected to, or will attempt to connect to.
io.sails.url
// The transports that the socket will attempt to connect using.
io.sails.transports
// Used for creating new socket connections manually.
io.sails.connect([url], [options])
// Unbind the specified event handler (opposite of .on()).
// To force a client socket to stop receiving broadcasted messages, do not use this method.
// Instead, unsubscribe the socket in your server-side code:
// In order to use .off(), you will need to store the handlerFn argument you passed in to .on() in a variable.
io.socket.off(eventIdentity, handlerFn)
// Start listening for socket events from Sails with the specified eventName.
// Will trigger the provided callback function when a matching event is received.
// This happens when the server broadcasts a message to this socket directly, or to a room of which it is a member.
io.socket.on(eventName, function (msg) { })
// Send a virtual DELETE request to a Sails server using Socket.io.
io.socket.delete(url, data, function (data, jwres) {})
// Send a socket request(virtual GET) to a Sails server using Socket.io.
io.socket.get(url, data, function (resData, jwres) {})
// Send a socket request (virtual PATCH) to a Sails server using Socket.io.
io.socket.patch(url, data, function (resData, jwres) {})
// Send a socket request (virtual POST) to a Sails server using Socket.io.
io.socket.post(url, data, function (resData, jwres) {})
// Send a socket request (virtual PUT) to a Sails server using Socket.io.
io.socket.put(url, data, function (resData, jwres) {})
// Send a virtual request to a Sails server using Socket.io.
io.socket.request(options, function (resData, jwres) {})
================================================
FILE: commitlint.config.js
================================================
module.exports = {extends: ['@commitlint/config-conventional']}
================================================
FILE: databases/mongodb.sh
================================================
# *****************************************************************************
# BASICS
# *****************************************************************************
# Connect MongoDB Shell
mongo # connects to mongodb://127.0.0.1:27017 by default
mongo --host --port -u -p # omit the password if you want a prompt
# Show All Databases
show dbs
# Show Current Database
db
# Create Or Switch Database
use
# Drop Database
db.dropDatabase()
# Create Collection
db.createCollection('posts')
# Show Collections
show collections
# *****************************************************************************
# CRUD
# *****************************************************************************
# Insert Row
db.posts.insert({
title: 'Post One',
body: 'Body of post one',
category: 'News',
tags: ['news', 'events'],
user: {
name: 'John Doe',
status: 'author'
},
date: Date()
})
# Insert Multiple Rows
db.posts.insertMany([
{
title: 'Post Two',
body: 'Body of post two',
category: 'Technology',
date: Date()
},
{
title: 'Post Three',
body: 'Body of post three',
category: 'News',
date: Date()
},
{
title: 'Post Four',
body: 'Body of post three',
category: 'Entertainment',
date: Date()
}
])
# Get All Rows
db.posts.find()
# Get All Rows Formatted
db.posts.find().pretty()
# Find One Row
db.posts.findOne({ category: 'News' })
# Find Rows
db.posts.find({ category: 'News' })
# Find Specific Fields
db.posts.find({ title: 'Post One' }, {
title: 1,
author: 1
})
# Update Row
db.posts.update({ title: 'Post Two' },
{
title: 'Post Two',
body: 'New body for post 2',
date: Date()
},
{
upsert: true
})
# Update Specific Field
db.posts.update({ title: 'Post Two' },
{
$set: {
body: 'Body for post 2',
category: 'Technology'
}
})
# Delete Row
db.posts.remove({ title: 'Post Four' })
# *****************************************************************************
# OTHER FUNCTIONS
# *****************************************************************************
# Sort Rows
db.posts.find().sort({ title: 1 }).pretty() # asc
db.posts.find().sort({ title: -1 }).pretty() # desc
# Count Rows
db.posts.find().count()
db.posts.find({ category: 'news' }).count()
# Limit Rows
db.posts.find().limit(2).pretty()
# Chaining
db.posts.find().limit(2).sort({ title: 1 }).pretty()
# Foreach
db.posts.find().forEach(function(doc) {
print("Blog Post: " + doc.title)
})
# Increment Field (\$inc)
db.posts.update({ title: 'Post Two' },
{
$inc: {
likes: 5
}
})
# Rename Field
db.posts.update({ title: 'Post Two' },
{
$rename: {
likes: 'views'
}
})
# Sub-Documents
db.posts.update({ title: 'Post One' },
{
$set: {
comments: [
{
body: 'Comment One',
user: 'Mary Williams',
date: Date()
},
{
body: 'Comment Two',
user: 'Harry White',
date: Date()
}
]
}
})
# Find By Element in Array (\$elemMatch)
db.posts.find({
comments: {
$elemMatch: {
user: 'Mary Williams'
}
}
}
)
# Add Index
db.posts.createIndex({ title: 1 })
# Drop Index
db.posts.dropIndex("title_1")
# Hide/Unhide Indexes
db.posts.hideIndex("title_1")
db.posts.unhideIndex("title_1")
# Text Search
db.posts.find({
$text: {
$search: "\"Post O\""
}
})
# Greater & Less Than
db.posts.find({ views: { $gt: 2 } })
db.posts.find({ views: { $gte: 7 } })
db.posts.find({ views: { $lt: 7 } })
db.posts.find({ views: { $lte: 7 } })
================================================
FILE: databases/mysql.sh
================================================
# *****************************************************************************
# BASICS
# *****************************************************************************
mysqldump -h hostname -u username -p database_name -P port > file.sql # Export database
mysql -u username -p database_name < file.sql # Import database
SHOW PROCESSLIST; # Show you any queries that are currently running or in the queue to run
show status where `variable_name` = 'Threads_connected'; # Show all connected threads
show variables like 'max_connections'; # Show maximum number of allowed connections
SET GLOBAL max_connections = 150; ## Set new value for maximum connections (no restart needed but for permanent change update my.cnf)
GRANT ALL PRIVILEGES ON prospectwith.* TO 'power'@'localhost' WITH GRANT OPTION; # Grant all privileges on database
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password'; # Create user
mysql -u root -pmypassword -e "MY SQL QUERY" &>> query.log & disown # Run SQL query in the background
# *****************************************************************************
# Database and Table Operations
# *****************************************************************************
CREATE DATABASE database_name; # Create a new database
DROP DATABASE database_name; # Delete a database
CREATE TABLE table_name (column1 datatype, column2 datatype, ...); # Create a new table
DROP TABLE table_name; # Delete a table
SHOW TABLES; # Display all tables in the current database
DESCRIBE table_name; # Show the structure of a table
# *****************************************************************************
# Data Manipulation
# *****************************************************************************
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...); # Insert data into a table
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition; # Update existing data in a table
DELETE FROM table_name WHERE condition; # Delete data from a table
SELECT column1, column2, ... FROM table_name WHERE condition; # Select data from a table
# *****************************************************************************
# Backup and Restore
# *****************************************************************************
mysqldump -u username -p database_name table1 table2 > file.sql # Backup specific tables
mysql -u username -p database_name < file.sql # Restore specific tables
# *****************************************************************************
# User Management and Security
# *****************************************************************************
REVOKE privilege_type ON database_name.table_name FROM 'username'@'hostname'; # Revoke privileges from a user
DROP USER 'username'@'hostname'; # Delete a user
ALTER USER 'username'@'hostname' IDENTIFIED BY 'newpassword'; # Reset a user's password
# *****************************************************************************
# Performance and Maintenance
# *****************************************************************************
OPTIMIZE TABLE table_name; # Optimize a table
ANALYZE TABLE table_name; # Analyze a table for key distribution and storage optimization
CHECK TABLE table_name; # Check a table for errors
REPAIR TABLE table_name; # Repair a corrupted table
# *****************************************************************************
# Advanced Queries
# *****************************************************************************
SELECT ... FROM table1 JOIN table2 ON table1.column = table2.column; # Perform a join operation between two tables
SELECT ... FROM (SELECT ... FROM table_name) AS subquery; # Use a subquery within another query
SELECT column, COUNT(*) FROM table_name GROUP BY column; # Group results and use aggregate functions
# *****************************************************************************
# System Information
# *****************************************************************************
SELECT VERSION(); # Show the current version of MySQL
SELECT User, Host FROM mysql.user; # List all current MySQL users
# *****************************************************************************
# Miscellaneous
# *****************************************************************************
SET GLOBAL general_log = 'ON'; # Enable query logging
SHOW FULL PROCESSLIST; # Show the last queries executed in MySQL
================================================
FILE: databases/redis.sh
================================================
# *****************************************************************************
# BASICS
# *****************************************************************************
redis-server /path/redis.conf # start redis with the related configuration file
redis-cli # opens a redis prompt
sudo systemctl restart redis.service # Restart Redis
sudo systemctl status redis # Check Redis status
# *****************************************************************************
# STRINGS
# *****************************************************************************
APPEND key value # append a value to a key
BITCOUNT key [start end] # count set bits in a string
SET key value # set value in key
SETNX key value # set if not exist value in key
SETRANGE key offset value # overwrite part of a string at key starting at the specified offset
STRLEN key # get the length of the value stored in a key
MSET key value [key value ...] # set multiple keys to multiple values
MSETNX key value [key value ...] # set multiple keys to multiple values, only if none of the keys exist
GET key # get value in key
GETRANGE key start end # get substring of stored value from start to end offsets (both inclusive)
MGET key [key ...] # get the values of all the given keys
INCR key # increment value in key
INCRBY key increment # increment the integer value of a key by the given amount
INCRBYFLOAT key increment # increment the float value of a key by the given amount
DECR key # decrement the integer value of key by one
DECRBY key decrement # decrement the integer value of a key by the given number
DEL key # delete key
EXPIRE key 120 # key will be deleted in 120 seconds
TTL key # returns the number of seconds until a key is deleted
# *****************************************************************************
# LISTS
# A list is a series of ordered values
# *****************************************************************************
RPUSH key value [value ...] # put the new value at the end of the list
RPUSHX key value # append a value at the end of the list, only if it exists
LPUSH key value [value ...] # put the new value at the start of the list
LPUSHX key value # append a value at the start of the list, only if it exists
LRANGE key start stop # give a subset of the list
LINDEX key index # get an element from a list by its index
LINSERT key BEFORE|AFTER pivot value # insert an element before or after another element in a list
LLEN key # return the current length of the list
LPOP key # remove the first element from the list and returns it
LSET key index value # set the value of an element in a list by its index
LREM key number_of_occurrences value # delete occurrences of value if the list stored in key
LTRIM key start stop # trim a list to the specified range
RPOP key # remove the last element from the list and returns it
RPOPLPUSH source destination # remove the last element in a list, prepend it to another list and return it
BLPOP key [key ...] timeout # remove and get the first element in a list, or block until one is available
BRPOP key [key ...] timeout # remove and get the last element in a list, or block until one is available
# *****************************************************************************
# SETS
# A set is similar to a list, except it does not have a specific order
# and each element may only appear once.
# *****************************************************************************
SADD key member [member ...] # add the given value to the set
SCARD key # get the number of members in a set
SREM key member [member ...] # remove the given value from the set
SISMEMBER myset value # test if the given value is in the set.
SMEMBERS myset # return a list of all the members of this set
SUNION key [key ...] # combine two or more sets and returns the list of all elements
SINTER key [key ...] # intersect multiple sets
SMOVE source destination member # move a member from one set to another
SPOP key [count] # remove and return one or multiple random members from a set
# *****************************************************************************
# SORTED SETS
# A sorted set is similar to a regular set, but now each value has an associated score.
# This score is used to sort the elements in the set.
# *****************************************************************************
ZADD key [NX|XX] [CH] [INCR] score member [score member ...] # add one or more members to a sorted set, or update its score if it already exists
ZCARD key # get the number of members in a sorted set
ZCOUNT key min max # count the members in a sorted set with scores within the given values
ZINCRBY key increment member # increment the score of a member in a sorted set
ZRANGE key start stop [WITHSCORES] # returns a subset of the sorted set
ZRANK key member # determine the index of a member in a sorted set
ZREM key member [member ...] # remove one or more members from a sorted set
ZREMRANGEBYRANK key start stop # remove all members in a sorted set within the given indexes
ZREMRANGEBYSCORE key min max # remove all members in a sorted set, by index, with scores ordered from high to low
ZSCORE key member # get the score associated with the given mmeber in a sorted set
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count] # return a range of members in a sorted set, by score
# *****************************************************************************
# HASHES
# Hashes are maps between string fields and string values,
# so they are the perfect data type to represent objects.
# *****************************************************************************
HGET key field # get the value of a hash field
HGETALL key # get all the fields and values in a hash
HSET key field value # set the string value of a hash field
HSETNX key field value # set the string value of a hash field, only if the field does not exists
HMSET key field value [field value ...] # set multiple fields at once
HINCRBY key field increment # increment value in hash by X
HDEL key field [field ...] # delete one or more hash fields
HEXISTS key field # determine if a hash field exists
HKEYS key # get all the fields in a hash
HLEN key # get the number of fields in a hash
HSTRLEN key field # get the length of the value of a hash field
HVALS key # get all the values in a hash
# *****************************************************************************
# HYPERLOGLOG
# HyperLogLog uses randomization in order to provide an approximation of the number
# of unique elements in a set using just a constant, and small, amount of memory
# *****************************************************************************
PFADD key element [element ...] # add the specified elements to the specified HyperLogLog
PFCOUNT key [key ...] # return the approximated cardinality of the set(s) observed by the HyperLogLog at key's)
PFMERGE destkey sourcekey [sourcekey ...] # merge N HyperLogLogs into a single one
# *****************************************************************************
# PUBLICATION & SUBSCRIPTION
# *****************************************************************************
PSUBSCRIBE pattern [pattern ...] # listen for messages published to channels matching the given patterns
PUBSUB subcommand [argument [argument ...]] # inspect the state of the Pub/Sub subsystem
PUBLISH channel message # post a message to a channel
PUNSUBSCRIBE [pattern [pattern ...]] # stop listening for messages posted to channels matching the given patterns
SUBSCRIBE channel [channel ...] # listen for messages published to the given channels
UNSUBSCRIBE [channel [channel ...]] # stop listening for messages posted to the given channels
# *****************************************************************************
# OTHER COMMANDS
# *****************************************************************************
KEYS pattern # find all keys matching the given pattern
================================================
FILE: frontend/angular.js
================================================
/* *******************************************************************************************
* ANGULAR (2+) CHEATSHEET
* BASED ON https://angular.io/guide/cheatsheet
* DOCUMENTATION: https://angular.io/docs
* STYLE GUIDE: https://angular.io/guide/styleguide
* ******************************************************************************************* */
```
npm install --save @angular/cli // install command line interface (CLI) for Angular apps
ng serve // serve the app
ng build // build the release
```
/* *******************************************************************************************
* BOOSTRAPPING
* https://angular.io/guide/bootstrapping
* ******************************************************************************************* */
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
// Bootstraps the app, using the root component from the specified NgModule.
platformBrowserDynamic().bootstrapModule(AppModule);
/* *******************************************************************************************
* NG MODULES
* https://angular.io/guide/ngmodules
* ******************************************************************************************* */
import { NgModule } from '@angular/core';
@NgModule({
declarations: ...,
imports: ...,
exports: ...,
providers: ...,
bootstrap: ...
})
// Defines a module that contains components, directives, pipes, and providers.
class MyModule {}
// List of components, directives, and pipes that belong to this module.
declarations: [MyRedComponent, MyBlueComponent, MyDatePipe]
// List of modules to import into this module. Everything from the imported modules is available
// to declarations of this module.
imports: [BrowserModule, SomeOtherModule]
// List of components, directives, and pipes visible to modules that import this module.
exports: [MyRedComponent, MyDatePipe]
// List of dependency injection providers visible both to the contents of this module and to
// importers of this module.
providers: [MyService, { provide: ... }]
// List of components to bootstrap when this module is bootstrapped.
bootstrap: [MyAppComponent]
/* *******************************************************************************************
* TEMPLATE SYNTAX
* https://angular.io/guide/template-syntax
* ******************************************************************************************* */
// Binds property value to the result of expression firstName.
//
// Binds attribute role to the result of expression myAriaRole.
//
// Binds the presence of the CSS class extra-sparkle on the element to the truthiness of the
// expression isDelightful.
//
// Binds style property width to the result of expression mySize in pixels. Units are optional.
//
// Calls method readRainbow when a click event is triggered on this button element (or its
// children) and passes in the event object.
//