Category: Blog

  • auth0-example-client

    Auth0 Demonstration Client

    Thanks for your interest in my demonstration client of Auth0’s APIs. This is one half of a project demonstrating how one might go about implementing Auth0’s authentication API to interact with a custom backend.

    This repository houses the JavaScript-based frontend server, using the Ember.js framework. The accompanying PHP-based backend server can be found here.

    Screenshot

    Requirements

    Getting Started

    You should begin by cloning and configuring the backend counterpart to this project first. Instructions for that can be found in it’s repository.

    Next, clone this repository to your local machine:

    git clone https://github.com/evansims/auth0-example-client.git
    

    Quick Start Video Guide

    Watch the quick start video

    Configure Auth0 application

    1. Sign up for an Auth0 account, if you don’t already have one, and sign in.
    2. Open Auth0’s Applications dashboard and create a new Single Page Web Application.
    3. In your new Application’s settings, make note of your unique Client ID and Domain. You will need these later.
    4. Set the ‘Allowed Callback URLs’ endpoint to http://localhost:3000/callback.
    5. Save your Application settings changes.

    Configure our client

    1. On your machine, within the cloned directory of this repository, open the config/environment.js file.
    2. Find the auth0 section.
    3. Set your clientId and domain to the values you made note of when you set up your Auth0 Application (above.)
    4. Set your audience to match the Audience of the Auth0 API you noted while configuring the backend server.
    5. Save the file.

    Build the client

    This project assumes you have an existing Docker installation to simplify getting started. However, if you already have a working Ember CLI installation on your local machine you can build the project using the standard command line tools if you prefer.

    We’ll be using docker-sync to help streamline the build process across platforms. Once you have docker-sync installed, open your shell to the cloned repository on your local machine and run:

    $ docker-sync-stack start
    

    This will begin a file sync to the Docker container and start the build process. This may take a few minutes to complete.

    Once the build is done, your frontend will be accessible at http://localhost:3000 on your local machine.

    To terminate the build process at any time, simply close the shell process, which on most platforms is usually accomplished by pressing CTRL+C.

    Using the client

    Open http://localhost:3000 on your local machine to use the client.

    This client demonstrates a few simple aspects:

    After signing into the demonstration client with your Auth0 account, you will see a list of other users in your application.

    You can paginate and view more users by selecting the ‘more users’ button at the bottom of the results.

    At the top of the page you can use the search field to filter your results.

    The important points

    If you’re just looking for inspiration on how to do the important bits this client demonstrates, here’s where to look:

    • All session handling is done in the app/services/session.js file.
      • The application route (app/routes/application.js) is the root route and always the first route called in an Ember app.
        • We use this opportunity to have Auth0’s SPA SDK check if the user has already authenticated. This automatically happens when we create the Auth0Client instance in our Session service’s getSession method.
      • We have a method for getting some basic information about the authenticated user, getUser.
      • We have a sign out method, releaseSession.
    • We have an Ember Data model representing all the user objects returned by the Management API at app/models/user.js
    • We use an Ember component for managing the calls to our custom backend and rendering the users at app/components/pages/accounts-list/component.js

    Auth0 Documentation

    • Documentation for Auth0’s APIs can be found here.
    • Quickstarts for a variety of use cases, languages and respective frameworks can be found here.

    Contributing

    Pull requests are welcome!

    Security Vulnerabilities

    If you discover a security vulnerability within this project, please send an e-mail to Evan Sims at hello@evansims.com. All security vulnerabilities will be promptly addressed.

    License

    This demonstration project is open-sourced software licensed under the MIT license.

    Visit original content creator repository https://github.com/evansims/auth0-example-client
  • Vigu

    Build Status Maintenance

    Vigu

    Authors Jens Riisom Schultz(backend), Johannes Skov Frandsen(frontend)

    Since 2012-03-20

    Vigu is a PHP error aggregation system, which collects all possible PHP errors and aggregates them in a Redis database. It includes a frontend to browse the data.

    This project is based on Zaphod and uses several other projects:

    Requirements

    • git is required for installation.
    • You need apache mod_rewrite.
    • You need the phpredis PHP extension.
    • You need a Redis server, dedicated to this application.

    Optionally you can use a gearman based variant of the daemon, adding the following dependencies:

    Documentation

    • Point your browser to the root of the site, to start browsing errors.

    Installing

    • Clone vigu from git, i.e. git clone http://github.com/localgod/Vigu.git Vigu
    • Run php composer.phar install from command line.
    • Copy vigu.ini.dist to vigu.ini and edit it.
    • Make a vhost, to point at the root of vigu or the web/ folder, or however you choose to serve the site.
    • Set the daemon up, using php handlers/daemon.php -I. The daemon should be running at all times, but it may ONLY run on the Vigu server.
    • Copy vigu.ini to handlers/vigu.ini.
    • Include handlers/shutdown.php before anything else, preferably through php.ini’s auto_prepend_file directive. It has no dependencies besides it’s configuration file, which must exist next to it, so you can safely deploy it alone, to all your servers.

    License

    Copyright 2012 Jens Riisom Schultz, Johannes Skov Frandsen

    Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0
    

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

    Visit original content creator repository https://github.com/localgod/Vigu
  • Vigu

    Build Status Maintenance

    Vigu

    Authors Jens Riisom Schultz(backend), Johannes Skov Frandsen(frontend)

    Since 2012-03-20

    Vigu is a PHP error aggregation system, which collects all possible PHP errors and aggregates them in a Redis database. It includes a frontend to browse the data.

    This project is based on Zaphod and uses several other projects:

    Requirements

    • git is required for installation.
    • You need apache mod_rewrite.
    • You need the phpredis PHP extension.
    • You need a Redis server, dedicated to this application.

    Optionally you can use a gearman based variant of the daemon, adding the following dependencies:

    Documentation

    • Point your browser to the root of the site, to start browsing errors.

    Installing

    • Clone vigu from git, i.e. git clone http://github.com/localgod/Vigu.git Vigu
    • Run php composer.phar install from command line.
    • Copy vigu.ini.dist to vigu.ini and edit it.
    • Make a vhost, to point at the root of vigu or the web/ folder, or however you choose to serve the site.
    • Set the daemon up, using php handlers/daemon.php -I. The daemon should be running at all times, but it may ONLY run on the Vigu server.
    • Copy vigu.ini to handlers/vigu.ini.
    • Include handlers/shutdown.php before anything else, preferably through php.ini’s auto_prepend_file directive. It has no dependencies besides it’s configuration file, which must exist next to it, so you can safely deploy it alone, to all your servers.

    License

    Copyright 2012 Jens Riisom Schultz, Johannes Skov Frandsen

    Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0
    

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

    Visit original content creator repository https://github.com/localgod/Vigu
  • nft-marketplace-vyper

    NFT Marketplace contract (VYPER)

    This is the VYPER version of the repository, you also can find a SOLIDITY version

    This is a repository to work with and create a NFT Marketplace in a javascript environment using hardhat.
    This is a backend repository, it also work with a frontend repository. However you absolutly can use this repository without the frontend part.

    Summary

    NFT Marketplace

    The NFT Marketplace contract creates a NFT marketplace where any NFT collection can be listed or bought
    Every user can withdraw the ETH from the NFT they sold.

    The NFT Marketplace allow you to :

    • listNft: List a NFT on the marketplace with a given ETH price from any collection.
    • buyNft: Buy a NFT on the marketplace from any collection.
    • updateNftListing: Update the ETH price of your listed NFTs.
    • cancelNftListing: Cancel the listing of your NFT.
    • withdrawProceeds: Withdraw the ETH from the NFTs you sold on the Marketplace.

    NFT Collections

    This repository comes with 2 NFTs contract, each creating a NFT collection.
    The constructor takes a mint fee in ETH and an array of token uris for each characters of the collection.

    This contract implements :

    • Chainlink VRF to pick a random NFT when the user mint.

    The NFT Collections allows you to :

    Prerequisites

    Please install or have installed the following:

    Installation

    1. Clone this repository

    git clone https://github.com/jrmunchkin/nft-marketplace
    cd nft-marketplace
    
    1. Install dependencies
    yarn
    

    Testnet Development

    If you want to be able to deploy to testnets, do the following. I suggest to use goerli network.

    cp .env.example .env

    Set your GOERLI_RPC_URL, and PRIVATE_KEY

    You can get a GOERLI_RPC_URL by opening an account at Alchemy. Follow the steps to create a new application.

    You also can work with Infura.

    You can find your PRIVATE_KEY from your ethereum wallet like metamask.

    To be able to fully use the NFT collections you will need an account on Pinata. It will help you to push your NFTs metadata on IPFS and create a pin for you. To use Pinata you will need an PINATA_API_KEY, a PINATA_API_SECRET and a PINATA_JWT that you can find in the developers section. Additionally use UPLOAD_TO_PINATA to push conditionally on pinata.

    If you want to use it with the frontend repository, You also can clone it and set your frontend path FRONT_END_FOLDER

    the UPDATE_FRONT_END set to true will update your frontend with the last deployed contract.

    Finally you can add a COINMARKETCAP_API_KEY if you want to use hardhat gas reporter. You can find one by registring to CoinMarketCap Developers.

    You can add your environment variables to the .env file:

    PRIVATE_KEY=<PRIVATE_KEY>
    GOERLI_RPC_URL=<RPC_URL>
    COINMARKETCAP_API_KEY=<YOUR_API_KEY>
    FRONT_END_FOLDER=<YOUR_PATH_TO_FRONTEND>
    UPDATE_FRONT_END=<TRUE_OR_FALSE>
    PINATA_API_KEY=<YOUR_API_KEY>
    PINATA_API_SECRET=<YOUR_API_SECRET>
    PINATA_JWT=<YOUR_JWT>
    UPLOAD_TO_PINATA=<TRUE_OR_FALSE>

    You’ll also need testnet goerli ETH if you want to deploy on goerli tesnet. You can get ETH into your wallet by using the alchemy goerli faucet or chainlink faucet.

    Usage

    Deployment

    Feel free to change the mintFee variable in the helper-hardhat-config.js for setting your mint fee for the NFT collections.

    To deploy the contracts locally

    yarn hardhat deploy

    To deploy on goerli tesnet you need to create first a subscription on Chainlink VRF.
    Add the newly created subscriptionId to your helper-hardhat-config.js.

    To deploy the contracts on goerli tesnet

    yarn hardhat deploy --network goerli

    Once the contracts are deployed on goerli, you need to add them as a consumer to your subscription (Don’t forget to claim some LINK by using the chainlink faucet).

    To update the front end repository with the newly deployed contracts (You need to pull the frontend and set your FRONT_END_FOLDER first)

    yarn hardhat deploy --tags frontend

    Testing

    For unit testing

    yarn hardhat test
    

    For integration testing

    yarn hardhat test --network goerli
    

    Visit original content creator repository
    https://github.com/jrmunchkin/nft-marketplace-vyper

  • 2pc

    2pc

    This simple library allows you to create your own distributed transaction coordinator :

    case class Message(...)
    
    class CoordinatorImpl extends Coordinator[Message, TransactorImpl]
    
    class TransactorImpl extends Transactor[Message, ProcessorImpl] { //2nd phase
        override def complete = ...
        override def rollback = ...
        //def tid - transaction id (and also name of the actor)
    }
    
    class ProcessorImpl extends Processor[Task] { //1st phase
        def process(r: Req[Message]) = Future{...} //should return Commit or Rollback vote
        def complete(r: Req[Message]) = Future{...}
        def rollback(r: Req[Message]) = Future{...}
    }
    

    where

    • Message – is a message participating in transaction
    • Coordinator – is a supervisor
    • Transactor – implements 2PC protocol
    • Processor – is an actor which actually does the job

    Just implement complete/rollback to adopt this to your underlying system like JDBC, JMS or some other messaging protocol.

    To send set of messages, participating in one distributed transaction, use:

      val coordinator = system.actorOf(Props(classOf[CoordinatorImpl]), "coordinator")
      val request = ReqSeq(tid, Seq(msg1, ..., msgN))
      coordinator ! request
    

    where

    • tid – is unique id which correlates messages in XA transaction

    If you want to reduce data from processors to some actor – just point them to one tid-scoped actor

     class Receiver() extends Actor { ... }
     
     //in your supervisor
     context.child(tid) getOrElse context.actorOf(Props[Receiver], tid)
     
     //in your message
     case class Message(a: ActorRef, e: Option[Throwable], ...)
     
     //in processor (data with same tid will arrive sequentially)
     def process(r: Req[Message]) = r.req.a ? res
     
     
     
     def complete(m: Req[Message]) = m.body.a ! Done
     def rollback(m: Req[Message]) = m.body.a ! m.e //or m.a ! PoisonPill
    

    Some protocols may send data chunk by chunk. You can use chunked transaction to have every chunk processed immediately:

    import Helper._
    import Helper.implic.defaultAskTimeout
    implicit val expectations = 5.expected[Message]
    val chunk1 = ReqSeq("100500", Seq(msg1, msg2, msg3))   
    coordinator ! chunk1
    coordinator ! <something_else>
    val chunk2 = ReqSeq("100500", Seq(msg4, msg5))
    val result = coordinator ? chunk2
    

    Expectation is the count of messages which expected to be received in current transaction. Note that you have to specify real expectation (full count of messages in transaction) only for last chunk – just use 0 for all previous.

    You may want implement Merge trait to customize voting process or have end-of-transaction predicate more customized:

    class MyMerge(acc: Seq[Msg], votes: Seq[Vote[Msg]]) extends Merge[Msg] { 
       def isFull: Boolean = ... //should be true if all parts of chunked transaction received
       def mergeVotes = ...  //returns Commit[T] _ or Rollback[T] _ based on votes
    }
    
    implicit val merge = MyMerge
    
    val request = new ReqSeq(...)
    

    Visit original content creator repository
    https://github.com/dk14/2pc

  • discord-uwu-bot

    discord-uwu-bot

    A Discord bot that translates regular text into UwU-speak.

    Examples

    English UwU
    Hello, world! Hewlo, wowld! UwU!
    Lorem ipsum dolar sit amet Lowem ipsum dolaw sit amet UwU!
    I’ll have you know I graduated top of my class in the Navy Seals I’wl have you knyow I gwawduatewd top of my class in dwe Nyavy Seals UwU!

    Commands

    • uwu*that – Uwuify a message in chat. Reply to a message to uwuifiy it.
    • uwu*this – Uwuify text. The rest of the message will be uwuified.
    • uwu*me – Follow the sender and translate everything that they say in the current channel.
    • uwu*stop [where] – Stop following the sender. Optionally set where to “channel”, “server”, or “everywhere” to stop following in the current channel, current server, or in all of Discord, respectively. Defaults to “channel”.
    • uwu*stop_everyone [where] – Stop following everyone in the current channel or server. Optionally set where to “channel” or “server” to specify where to stop following. Defaults to “channel”. Requires “Manage Messages” permission.
    • uwu*them <user> – Follow a specified user and translate everything that they say in the current channel. Requires “Manage Messages” permission. Use the command again to stop following.

    Configuration

    The bot can be configured through a JSON configuration file, located at /opt/UwuBot/appsettings.Production.json by default.
    You must add your Discord token here before using the bot.
    If you are using the the install script, then a default configuration file will be provided for you.
    To create a configuration file manually, start with this template:

    {
      "DiscordAuth": {
        "DiscordToken": "YOUR DISCORD TOKEN HERE",
      },
      "BotOptions": {
        "CommandPrefixes": [ "uwu*" ]
      },
      "UwuOptions": {
        "AppendUwu": true,
        "MakeCuteCurses": true
      }
    }
    

    The following options are available to customize the bot behavior:

    Option Description Default
    BotOptions:CommandPrefixes List of command prefixes to respond to. [ "uwu*" ]
    UwuOptions:AppendUwu Appends a trailing “UwU!” to the text. true
    UwuOptions:MakeCuteCurses Replaces curse words with cuter, more UwU versions. true

    Discord Requirements (OAuth2)

    To join the bot to a server, you must grant permissions integer 2048. This consists of:

    • bot scope
    • Send Messages permission

    You must also grant the “Message Content” intent in the Discord Developer Portal.

    System Requirements

    • .NET 6+
    • Windows, Linux, or MacOS. A version of Linux with SystemD (such as Ubuntu) is required to use the built-in install script and service definition.

    Setup

    Before you can run discord-uwu-bot, you need a Discord API Token.
    You can get this token by creating and registering a bot at the Discord Developer Portal.
    You can use any name or profile picture for your bot.
    Once you have registered the bot, generate and save a Token.

    Ubuntu / SystemD Linux

    For Ubuntu (or other SystemD-based Linux systems), an install script and service definition are provided.
    This install script will create a service account (default uwubot), a working directory (default /opt/UwuBot), and a SystemD service (default uwubot).
    This script can update an existing installation and will preserve the appsettings.Production.json file containing your Discord Token and other configuration values.

    1. Compile the bot or download pre-built binaries.
    2. Run sudo ./install.sh.
    3. [First install only] Edit /opt/UwuBot/appsettings.Production.json and add your Discord token.
    4. Run sudo systemctl start uwubot to start the bot.

    Other OS

    For non-Ubuntu systems, manual setup is required.
    The steps below are the bare minimum to run the bot, and do not include steps needed to create a persistent service.

    1. Compile the bot or download pre-built binaries.
    2. Edit appsettings.Production.json and add your Discord token.
    3. Run dotnet DiscordUwuBot.Main.dll to start the bot.

    Visit original content creator repository
    https://github.com/warriordog/discord-uwu-bot

  • discord-uwu-bot

    discord-uwu-bot

    A Discord bot that translates regular text into UwU-speak.

    Examples

    English UwU
    Hello, world! Hewlo, wowld! UwU!
    Lorem ipsum dolar sit amet Lowem ipsum dolaw sit amet UwU!
    I’ll have you know I graduated top of my class in the Navy Seals I’wl have you knyow I gwawduatewd top of my class in dwe Nyavy Seals UwU!

    Commands

    • uwu*that – Uwuify a message in chat. Reply to a message to uwuifiy it.
    • uwu*this – Uwuify text. The rest of the message will be uwuified.
    • uwu*me – Follow the sender and translate everything that they say in the current channel.
    • uwu*stop [where] – Stop following the sender. Optionally set where to “channel”, “server”, or “everywhere” to stop following in the current channel, current server, or in all of Discord, respectively. Defaults to “channel”.
    • uwu*stop_everyone [where] – Stop following everyone in the current channel or server. Optionally set where to “channel” or “server” to specify where to stop following. Defaults to “channel”. Requires “Manage Messages” permission.
    • uwu*them <user> – Follow a specified user and translate everything that they say in the current channel. Requires “Manage Messages” permission. Use the command again to stop following.

    Configuration

    The bot can be configured through a JSON configuration file, located at /opt/UwuBot/appsettings.Production.json by default.
    You must add your Discord token here before using the bot.
    If you are using the the install script, then a default configuration file will be provided for you.
    To create a configuration file manually, start with this template:

    {
      "DiscordAuth": {
        "DiscordToken": "YOUR DISCORD TOKEN HERE",
      },
      "BotOptions": {
        "CommandPrefixes": [ "uwu*" ]
      },
      "UwuOptions": {
        "AppendUwu": true,
        "MakeCuteCurses": true
      }
    }
    

    The following options are available to customize the bot behavior:

    Option Description Default
    BotOptions:CommandPrefixes List of command prefixes to respond to. [ "uwu*" ]
    UwuOptions:AppendUwu Appends a trailing “UwU!” to the text. true
    UwuOptions:MakeCuteCurses Replaces curse words with cuter, more UwU versions. true

    Discord Requirements (OAuth2)

    To join the bot to a server, you must grant permissions integer 2048. This consists of:

    • bot scope
    • Send Messages permission

    You must also grant the “Message Content” intent in the Discord Developer Portal.

    System Requirements

    • .NET 6+
    • Windows, Linux, or MacOS. A version of Linux with SystemD (such as Ubuntu) is required to use the built-in install script and service definition.

    Setup

    Before you can run discord-uwu-bot, you need a Discord API Token.
    You can get this token by creating and registering a bot at the Discord Developer Portal.
    You can use any name or profile picture for your bot.
    Once you have registered the bot, generate and save a Token.

    Ubuntu / SystemD Linux

    For Ubuntu (or other SystemD-based Linux systems), an install script and service definition are provided.
    This install script will create a service account (default uwubot), a working directory (default /opt/UwuBot), and a SystemD service (default uwubot).
    This script can update an existing installation and will preserve the appsettings.Production.json file containing your Discord Token and other configuration values.

    1. Compile the bot or download pre-built binaries.
    2. Run sudo ./install.sh.
    3. [First install only] Edit /opt/UwuBot/appsettings.Production.json and add your Discord token.
    4. Run sudo systemctl start uwubot to start the bot.

    Other OS

    For non-Ubuntu systems, manual setup is required.
    The steps below are the bare minimum to run the bot, and do not include steps needed to create a persistent service.

    1. Compile the bot or download pre-built binaries.
    2. Edit appsettings.Production.json and add your Discord token.
    3. Run dotnet DiscordUwuBot.Main.dll to start the bot.

    Visit original content creator repository
    https://github.com/warriordog/discord-uwu-bot

  • NextAi

    This is a new React Native project, bootstrapped using @react-native-community/cli.
    Download Application(.apk)

    Getting Started

    Note: Make sure you have completed the React Native – Environment Setup instructions till “Creating a new application” step, before proceeding.

    Step 1: Start the Metro Server

    First, you will need to start Metro, the JavaScript bundler that ships with React Native.

    To start Metro, run the following command from the root of your React Native project:

    # using npm
    npm start
    
    # OR using Yarn
    yarn start

    Step 2: Start your Application

    Let Metro Bundler run in its own terminal. Open a new terminal from the root of your React Native project. Run the following command to start your Android or iOS app:

    For Android

    # using npm
    npm run android
    
    # OR using Yarn
    yarn android

    For iOS

    # using npm
    npm run ios
    
    # OR using Yarn
    yarn ios

    If everything is set up correctly, you should see your new app running in your Android Emulator or iOS Simulator shortly provided you have set up your emulator/simulator correctly.

    This is one way to run your app — you can also run it directly from within Android Studio and Xcode respectively.

    Step 3: Modifying your App

    Now that you have successfully run the app, let’s modify it.

    1. Open App.tsx in your text editor of choice and edit some lines.

    2. For Android: Press the R key twice or select “Reload” from the Developer Menu (Ctrl + M (on Window and Linux) or Cmd ⌘ + M (on macOS)) to see your changes!

      For iOS: Hit Cmd ⌘ + R in your iOS Simulator to reload the app and see your changes!

    Congratulations! 🎉

    You’ve successfully run and modified your React Native App. 🥳

    Now what?

    Troubleshooting

    If you can’t get this to work, see the Troubleshooting page.

    Learn More

    To learn more about React Native, take a look at the following resources:

    Visit original content creator repository
    https://github.com/02shreyansh/NextAi

  • JSONSchema

    JSONSchema

    Build Status
    Test Status

    This is an implementation of JSON Schema for the pharo language. It is used to define the structure and values of a JSON string and to validate it. The schema itself can be externalized for being consumed by a third party.

    DISCLAIMER: This is not a full implementation of the json schema spec. Basic types and constraints should work. If you need support for something not implemented you are invited to provide a pull request for it. If you cannot develop it you still can open a ticket in this repository

    It can be loaded by downloading it in pharo via

      Metacello new
        repository: 'github://zweidenker/JSONSchema';
        baseline: #JSONSchema;
        load
    

    Defining a schema

    These are the expression to create a schema model inside pharo.

    schema := {
      #name -> JSONSchema string.
      #dateAndTime -> (JSONSchema stringWithFormat: 'date-time').
      #numberOfPets -> JSONSchema number } asJSONSchema.
    
    

    defines as schema that can parse the following JSON:

    jsonString := '{
      "name" : "John Doe",
      "dateAndTime" : "1970-01-01T14:00:00",
      "numberOfPets" : 3
    }'.
    

    Reading/Writing a value using a schema

    To parse the value from JSON we only need to invoke:

    value := schema readString: jsonString
    

    The object in value will have name as a string, dateAndTime as a DateAndTime object and numberOfPets as a SmallInteger object.

    The schema can also be used to write out the value as JSON. This is especially useful if we want to ensure that only valid JSON is written. For this invoke

    jsonString := schema write: value.
    

    Serialize/Materialize a schema

    Addtionally to reading and writing objects a schema can be serialized to string.

    schemaString := NeoJSONWriter toStringPretty: schema.
    

    gives

    {
    	"type" : "object",
    	"properties" : {
    		"name" : {
    			"type" : "string"
    		},
    		"numberOfPets" : {
    			"type" : "number"
    		},
    		"dateAndTime" : {
    			"type" : "string",
    			"format" : "date-time"
    		}
    	}
    }
    

    If we would get a schema as string we can instantiate by invoking

    schema := JSONSchema fromString: schemaString.
    

    Nested schemas

    Schemas can be nested in any depth. And it can be specified by using the literal Array syntax.

    schema := {
      #name -> JSONSchema string.
      #address -> {
        #street -> JSONSchema string.
        #number -> JSONSchema number
      } } asJSONSchema
    

    Constraints

    JSON Schema has a defined set of constraints that can be specified. E.g. for a number the inerval of the value can be specified by

    numberSchema := JSONSchema number.
    numberSchema interval
      minimum: 1;
      exclusiveMaximum: 100
    

    constraining the number value to be greater or equal to 1 and smaller than 100.

    Visit original content creator repository
    https://github.com/zweidenker/JSONSchema

  • JSONSchema

    JSONSchema

    Build Status Test Status

    This is an implementation of JSON Schema for the pharo language. It is used to define the structure and values of a JSON string and to validate it. The schema itself can be externalized for being consumed by a third party.

    DISCLAIMER: This is not a full implementation of the json schema spec. Basic types and constraints should work. If you need support for something not implemented you are invited to provide a pull request for it. If you cannot develop it you still can open a ticket in this repository

    It can be loaded by downloading it in pharo via

      Metacello new
        repository: 'github://zweidenker/JSONSchema';
        baseline: #JSONSchema;
        load
    

    Defining a schema

    These are the expression to create a schema model inside pharo.

    schema := {
      #name -> JSONSchema string.
      #dateAndTime -> (JSONSchema stringWithFormat: 'date-time').
      #numberOfPets -> JSONSchema number } asJSONSchema.
    
    

    defines as schema that can parse the following JSON:

    jsonString := '{
      "name" : "John Doe",
      "dateAndTime" : "1970-01-01T14:00:00",
      "numberOfPets" : 3
    }'.
    

    Reading/Writing a value using a schema

    To parse the value from JSON we only need to invoke:

    value := schema readString: jsonString
    

    The object in value will have name as a string, dateAndTime as a DateAndTime object and numberOfPets as a SmallInteger object.

    The schema can also be used to write out the value as JSON. This is especially useful if we want to ensure that only valid JSON is written. For this invoke

    jsonString := schema write: value.
    

    Serialize/Materialize a schema

    Addtionally to reading and writing objects a schema can be serialized to string.

    schemaString := NeoJSONWriter toStringPretty: schema.
    

    gives

    {
    	"type" : "object",
    	"properties" : {
    		"name" : {
    			"type" : "string"
    		},
    		"numberOfPets" : {
    			"type" : "number"
    		},
    		"dateAndTime" : {
    			"type" : "string",
    			"format" : "date-time"
    		}
    	}
    }
    

    If we would get a schema as string we can instantiate by invoking

    schema := JSONSchema fromString: schemaString.
    

    Nested schemas

    Schemas can be nested in any depth. And it can be specified by using the literal Array syntax.

    schema := {
      #name -> JSONSchema string.
      #address -> {
        #street -> JSONSchema string.
        #number -> JSONSchema number
      } } asJSONSchema
    

    Constraints

    JSON Schema has a defined set of constraints that can be specified. E.g. for a number the inerval of the value can be specified by

    numberSchema := JSONSchema number.
    numberSchema interval
      minimum: 1;
      exclusiveMaximum: 100
    

    constraining the number value to be greater or equal to 1 and smaller than 100.

    Visit original content creator repository https://github.com/zweidenker/JSONSchema