Andrew French

1605127860

Simple Orm library for Deno based on deno_mysql

Deno Simple Orm

dso is a simple ORM Library based on deno_mysql

Example

import {
  BaseModel,
  Defaults,
  dso,
  Field,
  FieldType,
  CharsetType,
  Index,
  IndexType,
  Join,
  Model,
  Where
} from "https://deno.land/x/dso@v1.0.0/mod.ts";

// Define a database model
@Model("users")
class UserModel extends BaseModel {
  // Character set for whole table. UTF-8 is default and is not necessary to define.
  charset: CharsetType.utf8;

  // The ! operator is needed for primary key since it's never null 
  @Field({
    type: FieldType.INT,
    primary: true,
    length: 11,
    autoIncrement: true
  })
  id: number;

  @Field({ type: FieldType.STRING, length: 30 })
  name: string;

  @Field({ type: FieldType.STRING, length: 30 })
  password: string;

  // Charset can be explicitly defined for each column.
  @Field({ type: FieldType.STRING, length: 60, charset: CharsetType.utf8mb4 })
  namespace: string;

  // Index can be created [index/unique/spatial/fulltext] for each field
  @Field({ type: FieldType.STRING, length: 30, unique: true })
  email: string;

  // Multi column index can be defined by decorated @Index
  @Index({ type: IndexType.UNIQUE, columns: ["username","namespace"] })
  public myUniqueIndex!: Index;
}

const userModel = dso.define(UserModel);

async function main() {
  // The database must be created before linking
  await dso.connect({
    hostname: "127.0.0.1",
    port: 3306,
    username: "root",
    password: "",
    db: "dbname"
  });

  /*  
    When installing or initializing a database,
    you can use dso.sync to synchronize the database model to the database.
    Use false as the parameter if you want to sync only newly added models,
    Use true as the parameter if you want to sync the whole defined models
    to the database tables.

    == WARNING! ==
    Using true as the parameter will reset your whole database! Use with caution.
  */
  await dso.sync(false);

  // You can add records using insert method
  const insertId = await userModel.insert({
    name: "user1",
    password: "password"
  });

  // You can use the Model.findById method to get a record
  const user = await userModel.findById(1);

  // You can use Where clause too to get a record. For more information on
  // clauses such as join, order, etc. please consult:
  // https://github.com/manyuanrong/sql-builder

  // findOne + Where
  const userWhere = await userModel.findOne(Where.from({ name: "user1" }));

  // findAll + Where
  const userAll = await userModel.findAll(Where.from({ name: "user1" }));

  // findAll + expr like
  const userLike = await userModel.findAll(Where.expr("name like 'user%'"));

  console.log("Found user by id:", user);
  console.log("Found user by where eq clause:", userWhere);
  console.log("All users by where eq clause:", userAll);
  console.log("All users by where like clause:", userLike);
  console.log("User has these columns in index:", user.myUniqueIndex.columns);
}
main();

Running

Since this library needs to use Typescript Decorators and other features, a custom tsconfig.json needs to be added. Example config file can be found here, or just copy the contents below and create a new tsconfig.json file in your root directory.

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "isolatedModules": false
  }
}

To run, use:

deno run --allow-net -c tsconfig.json main.ts

where main.ts is your Typescript file for Deno.

Top Level API

dso.showQueryLog

Set whether query debugging information is displayed

dso.showQueryLog = true;
dso.connect

You need to use this method to link to the database before you can manipulate the database

await dso.connect({
  hostname: "127.0.0.1", // database hostname
  port: 3306, // database port
  username: "root", // database username
  password: "", // database password
  db: "dbname" // database name. (tips: The database must be created before linking)
});
dso.define()

Add an annotated Model instance and return the instance.

@Model("users")
class UserModel extends BaseModel {
  @Field({
    type: FieldType.INT,
    primary: true,
    length: 11,
    autoIncrement: true
  })
  id!: number;

  @Field({ type: FieldType.STRING, length: 30 })
  name?: string;

  @Field({ type: FieldType.STRING, length: 30 })
  password: string;

  @Field({ 
    type: FieldType.STRING, 
    unique: true, 
    length: 20})
  phoneNumber?: string;
}
}

export default const userModel = dso.define(UserModel);

// userModel.findById(...)
// userModel.findAll(...)
// userModel.findOne(...)
// userModel.insert(...)
// userModel.update(...)
// userModel.delete(...)
dso.sync

When installing or initializing a database, you can use sync to synchronize the database model to the database.

// If set to FORCE, tables will be deleted before they are created,
// otherwise only new models will be synchronized.
const force = true; // force
await dso.sync(force);
dso.transaction(processor: (transaction: Transaction) => Promise): Promise

Create and start a transaction.

New Model instances must be obtained through getModel(Model). Otherwise, it will not be controlled by transactions.

const result = await dso.transaction<boolean>(async trans => {
  const userModel = trans.getModel(UserModel);
  const topicModel = trans.getModel(TopicModel);

  userId = await userModel.insert({ nickName: "foo", password: "bar", phoneNumber: "08135539123" });
  topicId = await topicModel.insert({ title: "zoo", userId });
  return true;
});

Top Level Types

FieldType
  • DATE
  • INT
  • TEXT
  • STRING
  • BOOLEAN
Field

Field type describes the following properties of a field

key type default value desc
type one of the FieldTypes null types of database fields
length number unfixed field length
primary boolean false database primary key?
default any null default values for fields
autoIncrement boolean false identify auto-increment fields. It can only be used for INT types
notNull boolean false identity fields can not be null
autoUpdate boolean false updated automatically according to the current timestamp. It can only be used for DATE types
unique boolean false database unique index?
spatial boolean false database spatial index?
fullText boolean false database fullText index?
index boolean false database non unique index?
Index

Following types of an index are available

key multi column
index true
unique true
spatial false
fulltext true
Character sets

list of valid character sets is based on https://dev.mysql.com/doc/refman/8.0/en/charset-charsets.html

Download Details:

Author: manyuanrong

Source Code: https://github.com/manyuanrong/dso

#deno #node #nodejs #javascript

What is GEEK

Buddha Community

Simple Orm library for Deno based on deno_mysql

Andrew French

1605127860

Simple Orm library for Deno based on deno_mysql

Deno Simple Orm

dso is a simple ORM Library based on deno_mysql

Example

import {
  BaseModel,
  Defaults,
  dso,
  Field,
  FieldType,
  CharsetType,
  Index,
  IndexType,
  Join,
  Model,
  Where
} from "https://deno.land/x/dso@v1.0.0/mod.ts";

// Define a database model
@Model("users")
class UserModel extends BaseModel {
  // Character set for whole table. UTF-8 is default and is not necessary to define.
  charset: CharsetType.utf8;

  // The ! operator is needed for primary key since it's never null 
  @Field({
    type: FieldType.INT,
    primary: true,
    length: 11,
    autoIncrement: true
  })
  id: number;

  @Field({ type: FieldType.STRING, length: 30 })
  name: string;

  @Field({ type: FieldType.STRING, length: 30 })
  password: string;

  // Charset can be explicitly defined for each column.
  @Field({ type: FieldType.STRING, length: 60, charset: CharsetType.utf8mb4 })
  namespace: string;

  // Index can be created [index/unique/spatial/fulltext] for each field
  @Field({ type: FieldType.STRING, length: 30, unique: true })
  email: string;

  // Multi column index can be defined by decorated @Index
  @Index({ type: IndexType.UNIQUE, columns: ["username","namespace"] })
  public myUniqueIndex!: Index;
}

const userModel = dso.define(UserModel);

async function main() {
  // The database must be created before linking
  await dso.connect({
    hostname: "127.0.0.1",
    port: 3306,
    username: "root",
    password: "",
    db: "dbname"
  });

  /*  
    When installing or initializing a database,
    you can use dso.sync to synchronize the database model to the database.
    Use false as the parameter if you want to sync only newly added models,
    Use true as the parameter if you want to sync the whole defined models
    to the database tables.

    == WARNING! ==
    Using true as the parameter will reset your whole database! Use with caution.
  */
  await dso.sync(false);

  // You can add records using insert method
  const insertId = await userModel.insert({
    name: "user1",
    password: "password"
  });

  // You can use the Model.findById method to get a record
  const user = await userModel.findById(1);

  // You can use Where clause too to get a record. For more information on
  // clauses such as join, order, etc. please consult:
  // https://github.com/manyuanrong/sql-builder

  // findOne + Where
  const userWhere = await userModel.findOne(Where.from({ name: "user1" }));

  // findAll + Where
  const userAll = await userModel.findAll(Where.from({ name: "user1" }));

  // findAll + expr like
  const userLike = await userModel.findAll(Where.expr("name like 'user%'"));

  console.log("Found user by id:", user);
  console.log("Found user by where eq clause:", userWhere);
  console.log("All users by where eq clause:", userAll);
  console.log("All users by where like clause:", userLike);
  console.log("User has these columns in index:", user.myUniqueIndex.columns);
}
main();

Running

Since this library needs to use Typescript Decorators and other features, a custom tsconfig.json needs to be added. Example config file can be found here, or just copy the contents below and create a new tsconfig.json file in your root directory.

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "isolatedModules": false
  }
}

To run, use:

deno run --allow-net -c tsconfig.json main.ts

where main.ts is your Typescript file for Deno.

Top Level API

dso.showQueryLog

Set whether query debugging information is displayed

dso.showQueryLog = true;
dso.connect

You need to use this method to link to the database before you can manipulate the database

await dso.connect({
  hostname: "127.0.0.1", // database hostname
  port: 3306, // database port
  username: "root", // database username
  password: "", // database password
  db: "dbname" // database name. (tips: The database must be created before linking)
});
dso.define()

Add an annotated Model instance and return the instance.

@Model("users")
class UserModel extends BaseModel {
  @Field({
    type: FieldType.INT,
    primary: true,
    length: 11,
    autoIncrement: true
  })
  id!: number;

  @Field({ type: FieldType.STRING, length: 30 })
  name?: string;

  @Field({ type: FieldType.STRING, length: 30 })
  password: string;

  @Field({ 
    type: FieldType.STRING, 
    unique: true, 
    length: 20})
  phoneNumber?: string;
}
}

export default const userModel = dso.define(UserModel);

// userModel.findById(...)
// userModel.findAll(...)
// userModel.findOne(...)
// userModel.insert(...)
// userModel.update(...)
// userModel.delete(...)
dso.sync

When installing or initializing a database, you can use sync to synchronize the database model to the database.

// If set to FORCE, tables will be deleted before they are created,
// otherwise only new models will be synchronized.
const force = true; // force
await dso.sync(force);
dso.transaction(processor: (transaction: Transaction) => Promise): Promise

Create and start a transaction.

New Model instances must be obtained through getModel(Model). Otherwise, it will not be controlled by transactions.

const result = await dso.transaction<boolean>(async trans => {
  const userModel = trans.getModel(UserModel);
  const topicModel = trans.getModel(TopicModel);

  userId = await userModel.insert({ nickName: "foo", password: "bar", phoneNumber: "08135539123" });
  topicId = await topicModel.insert({ title: "zoo", userId });
  return true;
});

Top Level Types

FieldType
  • DATE
  • INT
  • TEXT
  • STRING
  • BOOLEAN
Field

Field type describes the following properties of a field

key type default value desc
type one of the FieldTypes null types of database fields
length number unfixed field length
primary boolean false database primary key?
default any null default values for fields
autoIncrement boolean false identify auto-increment fields. It can only be used for INT types
notNull boolean false identity fields can not be null
autoUpdate boolean false updated automatically according to the current timestamp. It can only be used for DATE types
unique boolean false database unique index?
spatial boolean false database spatial index?
fullText boolean false database fullText index?
index boolean false database non unique index?
Index

Following types of an index are available

key multi column
index true
unique true
spatial false
fulltext true
Character sets

list of valid character sets is based on https://dev.mysql.com/doc/refman/8.0/en/charset-charsets.html

Download Details:

Author: manyuanrong

Source Code: https://github.com/manyuanrong/dso

#deno #node #nodejs #javascript

What is Base Protocol (BASE) | What is BASE token

Base Protocol (BASE) is a token whose price is pegged to the total market cap of all cryptocurrencies at a ratio of 1:1 trillion. BASE allows traders to speculate on the entire crypto industry with one token. The Base Protocol is built on the Ethereum blockchain, integrates a (Chainlink) oracle, and is launching on ((Uniswap)

As cryptocurrency enthusiasts, we’re sometimes divided on which digital assets to buy — bullish on certain projects and bearish on others.

But we all agree on one thing, which is that the overall cryptocurrency industry will achieve long-term growth and future adoption.

The Base Protocol makes it possible to invest with this consensus. BASE allows traders to speculate on the entire industry with one token.

Image for post

The Base Protocol is the world’s first and only tokenized cryptocurrency market tracker. By holding BASE tokens, users can get exposure to the performance of the entire cryptocurrency market. Unlike the index trackers currently operating in the traditional markets, there is no entry or exit fee or brokerage charges.

Index funds have consistently outperformed actively managed mutual funds. Until the launch of BASE, there was no real cryptocurrency market tracker that tracked the performance of the entire digital asset market. BASE will be useful for institutional investors and traders to diversify and hedge their crypto portfolios. BASE will also help new and existing retail investors to take out the guesswork and get exposed to the growth of all current and future digital assets entering the market.

The BASE token’s underlying protocol creates several additional use cases in DeFi, trading, venture capital, hedge funds and many other business sectors.

The Base Protocol mission is simple — to make it easy for everyone to benefit from the performance of the entire cryptocurrency market in a secure, decentralized and future-proof way.

Why BASE?

It’s no doubt that a crypto industry ETF would be a valuable product for investors. But it is very challenging to create such a product through traditional means, as it would be almost impossible to manage portfolio ownership of 5,000+ assets. How would the portfolio manager weigh ownership of each asset as market cap dominance changes? How would they account for newly entering/exiting assets? Who would take on all the associated transaction and custodial fees? There are also various legal limitations that restrict the formation of such an instrument in many countries — and even if it could be formed, it would be a highly centralized product.

By simply pegging price to the total market capitalization of all cryptocurrencies, the Base Protocol cuts through all of these problems. BASE gives holders the same function as a traditional industry ETF without all of the centralized challenges that make such an ETF impossible.

BASE will offer new value for investors in the cryptocurrency ecosystem through an elegantly simple protocol — so valuable and so simple that you might be asking yourself:

How has this not been done before?

The answer is that it wasn’t possible until recently. This project couldn’t be achieved without a robust decentralized blockchain, proven oracle integrations, and new developments in the DeFi space. We founded the Base Protocol to build on these innovations and create BASE; one tokenized asset that represents speculation on all cryptocurrencies.

Vision

We’ve seen that there are many individuals who want to invest in cryptocurrencies, but don’t necessarily understand how they work. While the overview for each different crypto asset can be difficult to understand for a new user, the pitch for BASE is simple: it’s the way to invest in all of those crypto assets simultaneously. In this way, the Base Protocol can become an instrumental force in driving new adoption in the blockchain space.

We’ve also noticed that institutional investors have been introducing cryptocurrency investments to their portfolios. These institutions typically invest at a high level with great diversification covering multiple industries. Their cryptocurrency holdings are usually composed of just Bitcoin, or some handful mix of “blue chip” digital assets. By holding BASE, these institutions will gain exposure to the entire cryptocurrency industry — an objectively more diversified alternative.

In the same way that Bitcoin is the household name of cryptocurrencies, the Base Protocol aims to become the household name for general cryptocurrency investing. BASE’s vision is to become the primary channel of investment for new/existing cryptocurrency traders and institutional investors.

Would you like to earn token right now! ☞ CLICK HERE

Looking for more information…

☞ Website
☞ Explorer
☞ Source Code
☞ Social Channel
Message Board
☞ Coinmarketcap

Create an Account and Trade NOW

Bittrex
Poloniex
Binance

Thank for visiting and reading this article! I’m highly appreciate your actions! Please share if you liked it!

#blockchain #bitcoin #crypto #base protocol #base

Welde Tekle

Welde Tekle

1597865220

A simple WebSocket library like ws of node.js library for deno

deno websocket

🦕 A simple WebSocket library like ws of node.js library for deno

  • Deno >= 1.2

Quick Start

Example Demo

demo

Server side

$ deno run --allow-net https://deno.land/x/websocket@v0.0.3/example/server.ts 

Client side

$ deno run --allow-net https://deno.land/x/websocket@v0.0.3/example/client.ts 
ws connected! (type 'close' to quit)
> something

Usage

Server side

import { WebSocket, WebSocketServer } from "https://deno.land/x/websocket@v0.0.3/mod.ts";

const wss = new WebSocketServer(8080);
wss.on("connection", function (ws: WebSocket) {
  ws.on("message", function (message: string) {
    console.log(message);
    ws.send(message)
  });
});

Client side

import { WebSocket } from "https://deno.land/x/websocket@v0.0.3/mod.ts";
const endpoint = "ws://127.0.0.1:8080";
const ws: WebSocket = new WebSocket(endpoint);
ws.on("open", function() {
  console.log("ws connected!");
});
ws.on("message", function (message: string) {
  console.log(message);
});
ws.send("something");

Documentation

WebSocketServer

Event

event detail
connection Emitted when the handshake is complete
error Emitted when an error occurs

Field

field detail type
server.clients A set that stores all connected clients Set<WebSocket>

Method

method detail
close() Close the server

WebSocket

Event

event detail
open Emitted when the connection is established
close Emitted when the connection is closed
message Emitted when a message is received from the server
ping Emitted when a ping is received from the server
pong Emitted when a pong is received from the server
error Emitted when an error occurs

Field

field detail type
websocket.isClose Get the close flag Boolean

Method

method detail
send(message:string Unit8Array)
ping(message:string Unit8Array)
close([code:int[, reason:string]]) Close the connection with the server
forceClose() Forcibly close the connection with the server

Download Details:

Author: ryo-ma

Demo: https://deno.land/x/websocket@v0.0.3

Source Code: https://github.com/ryo-ma/deno-websocket

#deno #node #nodejs #javascript

Gps Location Based App Development

In the search for trends, more and more geo-dependent mobile applications have been appearing on the market. Some of them cannot work without locating the user, while others are taking advantage of the geolocation feature to make their services more accessible. Navigators, guides, social networks with geotagged photos, fitness applications with route tracking belong to so-called Location-Based Services.

DataIT Solutions development expertise helps you get the most accurate GPS location-based solutions with highly-reliable GPS tracking modules including driving estimations, dynamic condition filtering, yielding the best consumer experience.

Location-Based App Development Helps In:

  • Identifying the position of a person or an object
  • Measurement of distance between two objects
  • Building optimum routes from one point to another

A location-based app needs an interactive UI along with strong backend server functionalities such as:

  • GPS coordinates of the location
  • Receiving the current location of the user
  • Serving the nearby locations
  • Directions for driving or walking
  • Map integration

We build innovative mobile apps that are instantly deployable for navigation & search, weather, field services, asset-tracking, proximity-based marketing, geofencing services, and more. Our beacon-compatible mobile applications deliver engaging UX for indoor-outdoor locations while enhancing existing business processes, productivity, and revenues.

Location-based apps are a great mobile development segment. It is still possible to come up with an innovative idea and become a giant in this enterprise.

Hire a Dedicated Development Team to develop your location-based apps and set your business apart from your competition.

#gps location based app development #app development #location based app development #gps location-based solutions #location-based app development #mobile-apps

Simple Graphviz library for Deno

graphviz

Graphviz library for Deno 🦕

Runtime independent APIs and specifications are compatible with the ts-graphviz package.

Usages

Callback style

renderDot function outputs the dot command execution result to the specified path by supplying diagram object.

renderDot function requires allow-write, allow-run permission, and dot command.

import * as path from "https://deno.land/std@0.67.0/path/mod.ts";
import { digraph, attribute, renderDot } from "https://deno.land/x/graphviz/mod.ts";

const G = digraph("G", (g) => {
  const a = g.node("aa");
  const b = g.node("bb");
  const c = g.node("cc");
  g.edge([a, b, c], {
    [attribute.color]: "red",
  });
  g.subgraph("A", (A) => {
    const Aa = A.node("Aaa", {
      [attribute.color]: "pink",
    });
    const Ab = A.node("Abb", {
      [attribute.color]: "violet",
    });
    const Ac = A.node("Acc");
    A.edge([Aa.port({ compass: "c" }), Ab, Ac, "E"], {
      [attribute.color]: "red",
    });
  });
});

const __dirname = new URL(".", import.meta.url).pathname;
await renderDot(G, path.resolve(__dirname, "./example.svg"), {
  format: "svg",
});

Script Style

Convert the diagram object to dot format with toDot function.

import { digraph, toDot } from "https://deno.land/x/graphviz/mod.ts";

const g = digraph("G");

const subgraphA = g.createSubgraph("A");
const nodeA1 = subgraphA.createNode("A_node1");
const nodeA2 = subgraphA.createNode("A_node2");
subgraphA.createEdge([nodeA1, nodeA2]);

const subgraphB = g.createSubgraph("B");
const nodeB1 = subgraphB.createNode("B_node1");
const nodeB2 = subgraphB.createNode("B_node2");
subgraphA.createEdge([nodeB1, nodeB2]);

const node1 = g.createNode("node1");
const node2 = g.createNode("node2");
g.createEdge([node1, node2]);

const dot = toDot(g);
console.log(dot);
digraph "G" {
  "node1";
  "node2";
  subgraph "A" {
    "A_node1";
    "A_node2";
    "A_node1" -> "A_node2";
    "B_node1" -> "B_node2";
  }
  subgraph "B" {
    "B_node1";
    "B_node2";
  }
  "node1" -> "node2";
}

Download Details:

Author: ts-graphviz

Demo: https://deno.land/x/graphviz@v0.2.1

Source Code: https://github.com/ts-graphviz/deno

#deno #nodejs #node #javascript