nid

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2024 License: MIT Imports: 10 Imported by: 0

README

nid

License CI Coverage Report Documentation Release

nid package provides human-readable named unique identifiers.

Overview

The package offers the following functionalities:

  • Named prefix: All identifiers have name prefix that makes them more readable.
  • Universally unique: Random part of identifier base is 8 bytes length that is comparable to commonly used UUIDv4 & ULID.
  • Sortable by time: All identifiers have 8 bytes length time prefix. They are sortable both in string & binary format and have sequential order by time.
  • Text, JSON & SQL Support: Identifiers implement multiple encoding reducing code needed to add manual conversion:
    • encoding.TextMarshaler, encoding.TextUnmarshaler for text encoding.
    • json.Marshaler, json.Unmarshaler for JSON encoding.
    • sql.Scanner, driver.Valuer for storing in SQL database.

Installation

To use this package in your Go project, you can import it using:

import "go.wamod.dev/nid"

Usage

To start creating named identifiers, create new Naming first:

var BookIDN = nid.MustNaming("book") // snake_case 

Create your resource type:

type Book struct {
    ID     nid.NID `json:"id"`
    Title  string  `json:"title"`
    Author string  `json:"author"`
}

Then whenever you need to generate new identifier for your resource use identifier Naming:

book := Book{
    ID:     BookIDN.New(),
    Title:  "The Hobbit",
    Author: "J.R.R. Tolkien",
}
Helpers
Parsing strings

To parse named identifier from string use Parse function:

bookID, err := nid.Parse("book_000034o5m20uo63o22umrn7kcs")

To parse base identifier from string using ParseBase function:

base, err := nid.ParseBase("000034o5m20uo63o22umrn7kcs")
if err != nil {
    // handle error
}

// Apply resource naming to identifier
bookID := BookIDN.Apply(base)
Converting to string

When you need to convert it to string format you can use String() method:

fmt.Print(bookID.String()) 
// Output:
// book_000034o5m20uo63o22umrn7kcs

Similarly, you can also get identifier base string value:

fmt.Print(bookID.Base().String())
// Output:
// 000034o5m20uo63o22umrn7kcs
Compare

To check if two named identifiers are the same you can use equal operator:

var (
    a nid.NID
    b nid.NID
)

if a == b {
    fmt.Print("a == b")
}

You can also use Compare helpers that return 0, -1, 1:

switch nid.Compare(a, b) {
    case 0:
        fmt.Print("a == b")
    case 1:
        fmt.Print("a > b")
    case -1:
        fmt.Print("a < b")
}

Similarly, you can also compare identifier base:

switch nid.CompareBase(a.Base(), b.Base()) {
    case 0:
        fmt.Print("a == b")
    case 1:
        fmt.Print("a > b")
    case -1:
        fmt.Print("a < b")
}
Sort

When you need to sort multiple identifiers you can use Sort helper:

var ids []nid.NID

nid.Sort(ids)

Similarly, you can also sort identifier base:

var baseIDs []nid.Base

nid.SortBase(baseIDs)

Contributing

Thank you for your interest in contributing to the nid Go library! We welcome and appreciate any contributions, whether they be bug reports, feature requests, or code changes.

If you've found a bug, please create an issue describing the problem, including any relevant error messages and a minimal reproduction of the issue.

License

nid is licensed under the MIT License.

Documentation

Overview

Package nid implements named unique sortable identifiers.

It's designed to provide a way to work with unique identifiers that are more human-readable. The identifiers are sortable and can be used in the database. The package also provides a way to convert the identifiers to and from the JSON, Text, and database values.

Example

Example demonstrates how to use the go.wamod.io/nid package.

package main

import (
	"fmt"

	"go.wamod.dev/nid"
)

func main() {
	// Create a new [nid.Naming] for books
	bookIDN := nid.MustNaming("book")

	// Create one new [nid.NID] for
	bookID := bookIDN.New()

	fmt.Printf("Book ID: %s", bookID)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrFailedParse = fmt.Errorf("nid: failed to parse")
	ErrInvalidName = fmt.Errorf("nid: invalid name")
)

Functions

func Compare

func Compare(a, b NID) int

Compare two NID identifiers.

func CompareBase

func CompareBase(a, b Base) int

CompareBase two Base identifiers

func Sort

func Sort(ids []NID)

Sort the [NID]s.

func SortBase

func SortBase(ids []Base)

SortBase the Base identifiers.

Types

type Base

type Base [baseLen]byte

Base of the NID with a time and random part. The time part is 8 bytes and the random part is 8 bytes. The total length is 16 bytes. The Base is sortable and unique.

func MustParseBase

func MustParseBase(src string) Base

MustParseBase is a helper to parse Base. It panics if the base is invalid.

func NewBase

func NewBase() Base

NewBase creates a new Base at the current time.

func NewBaseAt

func NewBaseAt(ts time.Time) Base

NewBaseAt creates a new Base for the given time. The time is in nanoseconds.

func ParseBase

func ParseBase(src string) (Base, error)

ParseBase parses the Base from the string.

func ParseBaseBytes

func ParseBaseBytes(src []byte) (dst Base, err error)

ParseBaseBytes parses the Base from the bytes.

func (Base) Bytes

func (base Base) Bytes() []byte

Bytes returns the bytes of the Base.

func (Base) Empty

func (base Base) Empty() bool

Empty returns true if the Base is empty.

func (Base) MarshalJSON

func (base Base) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON representation of the Base.

func (Base) MarshalText

func (base Base) MarshalText() ([]byte, error)

MarshalText returns the text representation of the Base.

func (*Base) Scan

func (base *Base) Scan(src any) (err error)

Scan scans the value into the Base.

func (Base) String

func (base Base) String() string

String returns the string representation of the Base.

func (Base) Time

func (base Base) Time() time.Time

Time returns the time of the Base.

func (Base) UnixMilli

func (base Base) UnixMilli() int64

Unix returns the time of the Base in seconds.

func (*Base) UnmarshalJSON

func (base *Base) UnmarshalJSON(src []byte) error

UnmarshalJSON parses the Base from the JSON.

func (*Base) UnmarshalText

func (base *Base) UnmarshalText(src []byte) error

UnmarshalText parses the Base from the text.

func (Base) Value

func (base Base) Value() (driver.Value, error)

Value returns the driver value of the Base.

type NID

type NID struct {
	// contains filtered or unexported fields
}

NID is a named identifier. It consists of the name and the base identifier that is sortable and unique.

func MustParse

func MustParse(str string) NID

MustParse is a helper to parse named NID. It panics if given string is invalid.

func Parse

func Parse(str string) (dst NID, err error)

Parse the named ID from the string.

func (NID) Base

func (id NID) Base() Base

Base returns the base identifier.

func (NID) Empty

func (id NID) Empty() bool

Empty returns true if the ID is empty.

func (NID) MarshalJSON

func (id NID) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON representation of the ID.

func (NID) MarshalText

func (id NID) MarshalText() ([]byte, error)

MarshalText returns the text representation of the ID.

func (NID) Name

func (id NID) Name() string

Name returns the name of the ID.

func (*NID) Scan

func (id *NID) Scan(src any) error

Scan the value into the ID.

func (NID) String

func (id NID) String() string

String returns the string representation of the ID. The format is "<name>_<id>".

func (*NID) UnmarshalJSON

func (id *NID) UnmarshalJSON(src []byte) error

UnmarshalJSON parses the ID from the JSON.

func (*NID) UnmarshalText

func (id *NID) UnmarshalText(data []byte) error

UnmarshalText parses the ID from the text.

func (NID) Value

func (id NID) Value() (driver.Value, error)

Value returns the driver value.

type Naming

type Naming struct {
	// contains filtered or unexported fields
}

Naming provides a way to create, update and validate the [NID]s.

func MustNaming

func MustNaming(name string) Naming

MustNaming is a helper to create Namer from the name. It panics if the name is invalid.

func NewNaming

func NewNaming(name string) (Naming, error)

NewNaming creates a new Naming from the name. It returns an error if the name is invalid. The name must be a non-empty snake_case string, e.g. "user" or "user_profile".

func (Naming) Apply

func (n Naming) Apply(base Base) NID

Apply create a new NID from the given Base.

func (Naming) Is

func (n Naming) Is(id NID) bool

Is checks if the name of the NID matches namer's name.

func (Naming) New

func (n Naming) New() NID

New creates a new NID at the current time.

func (Naming) NewAt

func (n Naming) NewAt(ts time.Time) NID

NewAt creates a new NID at the given time.

func (Naming) Update

func (n Naming) Update(id NID) NID

Update the name of the NID with the namer's name.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL