delete the generator, moved to m3o (#279)

This commit is contained in:
Asim Aslam
2021-11-18 12:58:40 +00:00
committed by GitHub
parent ef70da5380
commit 7f7a87c428
548 changed files with 0 additions and 30275 deletions

View File

@@ -1,67 +0,0 @@
name: Generate Clients & Examples
on: [push]
jobs:
generate:
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.13
uses: actions/setup-go@v2
with:
go-version: 1.13
id: go
- name: Install Protoc
uses: arduino/setup-protoc@master
- name: Check out this code
uses: actions/checkout@v2
with:
path: services
- name: Check out micro code
uses: actions/checkout@v2
with:
repository: 'micro/micro'
path: 'micro'
ref: 'master'
- name: Enable caching
uses: actions/cache@v2
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go-
- name: Install protoc gen micro plugin
working-directory: micro/cmd/protoc-gen-micro
run: |
go get -u github.com/golang/protobuf/protoc-gen-go
go install
- name: Install openapi plugin
working-directory: micro/cmd/protoc-gen-openapi
run: |
go install
- name: install prettier
working-directory: services
run: |
sudo npm install -g prettier
- name: Generate clients
working-directory: services
if: github.ref == 'refs/heads/master'
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
pwd
cd cmd/clients;
go install;
cd ../..;
clients .
- uses: EndBug/add-and-commit@v7
with:
cwd: './services'

View File

@@ -1,57 +0,0 @@
package address
import (
"github.com/micro/micro-go/client"
)
func NewAddressService(token string) *AddressService {
return &AddressService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type AddressService struct {
client *client.Client
}
// Lookup a list of UK addresses by postcode
func (t *AddressService) LookupPostcode(request *LookupPostcodeRequest) (*LookupPostcodeResponse, error) {
rsp := &LookupPostcodeResponse{}
return rsp, t.client.Call("address", "LookupPostcode", request, rsp)
}
type LookupPostcodeRequest struct {
// UK postcode e.g SW1A 2AA
Postcode string `json:"postcode"`
}
type LookupPostcodeResponse struct {
Addresses []Record `json:"addresses"`
}
type Record struct {
// building name
BuildingName string `json:"buildingName"`
// the county
County string `json:"county"`
// line one of address
LineOne string `json:"lineOne"`
// line two of address
LineTwo string `json:"lineTwo"`
// dependent locality
Locality string `json:"locality"`
// organisation if present
Organisation string `json:"organisation"`
// the postcode
Postcode string `json:"postcode"`
// the premise
Premise string `json:"premise"`
// street name
Street string `json:"street"`
// the complete address
Summary string `json:"summary"`
// post town
Town string `json:"town"`
}

View File

@@ -1,37 +0,0 @@
package answer
import (
"github.com/micro/micro-go/client"
)
func NewAnswerService(token string) *AnswerService {
return &AnswerService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type AnswerService struct {
client *client.Client
}
// Ask a question and receive an instant answer
func (t *AnswerService) Question(request *QuestionRequest) (*QuestionResponse, error) {
rsp := &QuestionResponse{}
return rsp, t.client.Call("answer", "Question", request, rsp)
}
type QuestionRequest struct {
// the question to answer
Query string `json:"query"`
}
type QuestionResponse struct {
// the answer to your question
Answer string `json:"answer"`
// any related image
Image string `json:"image"`
// a related url
Url string `json:"url"`
}

View File

@@ -1,113 +0,0 @@
package cache
import (
"github.com/micro/micro-go/client"
)
func NewCacheService(token string) *CacheService {
return &CacheService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type CacheService struct {
client *client.Client
}
// Decrement a value (if it's a number). If key not found it is equivalent to set.
func (t *CacheService) Decrement(request *DecrementRequest) (*DecrementResponse, error) {
rsp := &DecrementResponse{}
return rsp, t.client.Call("cache", "Decrement", request, rsp)
}
// Delete a value from the cache. If key not found a success response is returned.
func (t *CacheService) Delete(request *DeleteRequest) (*DeleteResponse, error) {
rsp := &DeleteResponse{}
return rsp, t.client.Call("cache", "Delete", request, rsp)
}
// Get an item from the cache by key. If key is not found, an empty response is returned.
func (t *CacheService) Get(request *GetRequest) (*GetResponse, error) {
rsp := &GetResponse{}
return rsp, t.client.Call("cache", "Get", request, rsp)
}
// Increment a value (if it's a number). If key not found it is equivalent to set.
func (t *CacheService) Increment(request *IncrementRequest) (*IncrementResponse, error) {
rsp := &IncrementResponse{}
return rsp, t.client.Call("cache", "Increment", request, rsp)
}
// Set an item in the cache. Overwrites any existing value already set.
func (t *CacheService) Set(request *SetRequest) (*SetResponse, error) {
rsp := &SetResponse{}
return rsp, t.client.Call("cache", "Set", request, rsp)
}
type DecrementRequest struct {
// The key to decrement
Key string `json:"key"`
// The amount to decrement the value by
Value int64 `json:"value,string"`
}
type DecrementResponse struct {
// The key decremented
Key string `json:"key"`
// The new value
Value int64 `json:"value,string"`
}
type DeleteRequest struct {
// The key to delete
Key string `json:"key"`
}
type DeleteResponse struct {
// Returns "ok" if successful
Status string `json:"status"`
}
type GetRequest struct {
// The key to retrieve
Key string `json:"key"`
}
type GetResponse struct {
// The key
Key string `json:"key"`
// Time to live in seconds
Ttl int64 `json:"ttl,string"`
// The value
Value string `json:"value"`
}
type IncrementRequest struct {
// The key to increment
Key string `json:"key"`
// The amount to increment the value by
Value int64 `json:"value,string"`
}
type IncrementResponse struct {
// The key incremented
Key string `json:"key"`
// The new value
Value int64 `json:"value,string"`
}
type SetRequest struct {
// The key to update
Key string `json:"key"`
// Time to live in seconds
Ttl int64 `json:"ttl,string"`
// The value to set
Value string `json:"value"`
}
type SetResponse struct {
// Returns "ok" if successful
Status string `json:"status"`
}

View File

@@ -1,120 +0,0 @@
package crypto
import (
"github.com/micro/micro-go/client"
)
func NewCryptoService(token string) *CryptoService {
return &CryptoService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type CryptoService struct {
client *client.Client
}
// Returns the history for the previous close
func (t *CryptoService) History(request *HistoryRequest) (*HistoryResponse, error) {
rsp := &HistoryResponse{}
return rsp, t.client.Call("crypto", "History", request, rsp)
}
// Get news related to a currency
func (t *CryptoService) News(request *NewsRequest) (*NewsResponse, error) {
rsp := &NewsResponse{}
return rsp, t.client.Call("crypto", "News", request, rsp)
}
// Get the last price for a given crypto ticker
func (t *CryptoService) Price(request *PriceRequest) (*PriceResponse, error) {
rsp := &PriceResponse{}
return rsp, t.client.Call("crypto", "Price", request, rsp)
}
// Get the last quote for a given crypto ticker
func (t *CryptoService) Quote(request *QuoteRequest) (*QuoteResponse, error) {
rsp := &QuoteResponse{}
return rsp, t.client.Call("crypto", "Quote", request, rsp)
}
type Article struct {
// the date published
Date string `json:"date"`
// its description
Description string `json:"description"`
// the source
Source string `json:"source"`
// title of the article
Title string `json:"title"`
// the source url
Url string `json:"url"`
}
type HistoryRequest struct {
// the crypto symbol e.g BTCUSD
Symbol string `json:"symbol"`
}
type HistoryResponse struct {
// the close price
Close float64 `json:"close"`
// the date
Date string `json:"date"`
// the peak price
High float64 `json:"high"`
// the low price
Low float64 `json:"low"`
// the open price
Open float64 `json:"open"`
// the crypto symbol
Symbol string `json:"symbol"`
// the volume
Volume float64 `json:"volume"`
}
type NewsRequest struct {
// cryptocurrency ticker to request news for e.g BTC
Symbol string `json:"symbol"`
}
type NewsResponse struct {
// list of articles
Articles []Article `json:"articles"`
// symbol requested for
Symbol string `json:"symbol"`
}
type PriceRequest struct {
// the crypto symbol e.g BTCUSD
Symbol string `json:"symbol"`
}
type PriceResponse struct {
// the last price
Price float64 `json:"price"`
// the crypto symbol e.g BTCUSD
Symbol string `json:"symbol"`
}
type QuoteRequest struct {
// the crypto symbol e.g BTCUSD
Symbol string `json:"symbol"`
}
type QuoteResponse struct {
// the asking price
AskPrice float64 `json:"askPrice"`
// the ask size
AskSize float64 `json:"askSize"`
// the bidding price
BidPrice float64 `json:"bidPrice"`
// the bid size
BidSize float64 `json:"bidSize"`
// the crypto symbol
Symbol string `json:"symbol"`
// the UTC timestamp of the quote
Timestamp string `json:"timestamp"`
}

View File

@@ -1,103 +0,0 @@
package currency
import (
"github.com/micro/micro-go/client"
)
func NewCurrencyService(token string) *CurrencyService {
return &CurrencyService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type CurrencyService struct {
client *client.Client
}
// Codes returns the supported currency codes for the API
func (t *CurrencyService) Codes(request *CodesRequest) (*CodesResponse, error) {
rsp := &CodesResponse{}
return rsp, t.client.Call("currency", "Codes", request, rsp)
}
// Convert returns the currency conversion rate between two pairs e.g USD/GBP
func (t *CurrencyService) Convert(request *ConvertRequest) (*ConvertResponse, error) {
rsp := &ConvertResponse{}
return rsp, t.client.Call("currency", "Convert", request, rsp)
}
// Returns the historic rates for a currency on a given date
func (t *CurrencyService) History(request *HistoryRequest) (*HistoryResponse, error) {
rsp := &HistoryResponse{}
return rsp, t.client.Call("currency", "History", request, rsp)
}
// Rates returns the currency rates for a given code e.g USD
func (t *CurrencyService) Rates(request *RatesRequest) (*RatesResponse, error) {
rsp := &RatesResponse{}
return rsp, t.client.Call("currency", "Rates", request, rsp)
}
type Code struct {
// e.g United States Dollar
Currency string `json:"currency"`
// e.g USD
Name string `json:"name"`
}
type CodesRequest struct {
}
type CodesResponse struct {
Codes []Code `json:"codes"`
}
type ConvertRequest struct {
// optional amount to convert e.g 10.0
Amount float64 `json:"amount"`
// base code to convert from e.g USD
From string `json:"from"`
// target code to convert to e.g GBP
To string `json:"to"`
}
type ConvertResponse struct {
// converted amount e.g 7.10
Amount float64 `json:"amount"`
// the base code e.g USD
From string `json:"from"`
// conversion rate e.g 0.71
Rate float64 `json:"rate"`
// the target code e.g GBP
To string `json:"to"`
}
type HistoryRequest struct {
// currency code e.g USD
Code string `json:"code"`
// date formatted as YYYY-MM-DD
Date string `json:"date"`
}
type HistoryResponse struct {
// The code of the request
Code string `json:"code"`
// The date requested
Date string `json:"date"`
// The rate for the day as code:rate
Rates map[string]float64 `json:"rates"`
}
type RatesRequest struct {
// The currency code to get rates for e.g USD
Code string `json:"code"`
}
type RatesResponse struct {
// The code requested e.g USD
Code string `json:"code"`
// The rates for the given code as key-value pairs code:rate
Rates map[string]float64 `json:"rates"`
}

View File

@@ -1,173 +0,0 @@
package db
import (
"github.com/micro/micro-go/client"
)
func NewDbService(token string) *DbService {
return &DbService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type DbService struct {
client *client.Client
}
// Count records in a table
func (t *DbService) Count(request *CountRequest) (*CountResponse, error) {
rsp := &CountResponse{}
return rsp, t.client.Call("db", "Count", request, rsp)
}
// Create a record in the database. Optionally include an "id" field otherwise it's set automatically.
func (t *DbService) Create(request *CreateRequest) (*CreateResponse, error) {
rsp := &CreateResponse{}
return rsp, t.client.Call("db", "Create", request, rsp)
}
// Delete a record in the database by id.
func (t *DbService) Delete(request *DeleteRequest) (*DeleteResponse, error) {
rsp := &DeleteResponse{}
return rsp, t.client.Call("db", "Delete", request, rsp)
}
// Drop a table in the DB
func (t *DbService) DropTable(request *DropTableRequest) (*DropTableResponse, error) {
rsp := &DropTableResponse{}
return rsp, t.client.Call("db", "DropTable", request, rsp)
}
// List tables in the DB
func (t *DbService) ListTables(request *ListTablesRequest) (*ListTablesResponse, error) {
rsp := &ListTablesResponse{}
return rsp, t.client.Call("db", "ListTables", request, rsp)
}
// Read data from a table. Lookup can be by ID or via querying any field in the record.
func (t *DbService) Read(request *ReadRequest) (*ReadResponse, error) {
rsp := &ReadResponse{}
return rsp, t.client.Call("db", "Read", request, rsp)
}
// Rename a table
func (t *DbService) RenameTable(request *RenameTableRequest) (*RenameTableResponse, error) {
rsp := &RenameTableResponse{}
return rsp, t.client.Call("db", "RenameTable", request, rsp)
}
// Truncate the records in a table
func (t *DbService) Truncate(request *TruncateRequest) (*TruncateResponse, error) {
rsp := &TruncateResponse{}
return rsp, t.client.Call("db", "Truncate", request, rsp)
}
// Update a record in the database. Include an "id" in the record to update.
func (t *DbService) Update(request *UpdateRequest) (*UpdateResponse, error) {
rsp := &UpdateResponse{}
return rsp, t.client.Call("db", "Update", request, rsp)
}
type CountRequest struct {
// specify the table name
Table string `json:"table"`
}
type CountResponse struct {
// the number of records in the table
Count int32 `json:"count"`
}
type CreateRequest struct {
// JSON encoded record or records (can be array or object)
Record map[string]interface{} `json:"record"`
// Optional table name. Defaults to 'default'
Table string `json:"table"`
}
type CreateResponse struct {
// The id of the record (either specified or automatically created)
Id string `json:"id"`
}
type DeleteRequest struct {
// id of the record
Id string `json:"id"`
// Optional table name. Defaults to 'default'
Table string `json:"table"`
}
type DeleteResponse struct {
}
type DropTableRequest struct {
Table string `json:"table"`
}
type DropTableResponse struct {
}
type ListTablesRequest struct {
}
type ListTablesResponse struct {
// list of tables
Tables []string `json:"tables"`
}
type ReadRequest struct {
// Read by id. Equivalent to 'id == "your-id"'
Id string `json:"id"`
// Maximum number of records to return. Default limit is 25.
// Maximum limit is 1000. Anything higher will return an error.
Limit int32 `json:"limit"`
Offset int32 `json:"offset"`
// 'asc' (default), 'desc'
Order string `json:"order"`
// field name to order by
OrderBy string `json:"orderBy"`
// Examples: 'age >= 18', 'age >= 18 and verified == true'
// Comparison operators: '==', '!=', '<', '>', '<=', '>='
// Logical operator: 'and'
// Dot access is supported, eg: 'user.age == 11'
// Accessing list elements is not supported yet.
Query string `json:"query"`
// Optional table name. Defaults to 'default'
Table string `json:"table"`
}
type ReadResponse struct {
// JSON encoded records
Records []map[string]interface{} `json:"records"`
}
type RenameTableRequest struct {
// current table name
From string `json:"from"`
// new table name
To string `json:"to"`
}
type RenameTableResponse struct {
}
type TruncateRequest struct {
Table string `json:"table"`
}
type TruncateResponse struct {
}
type UpdateRequest struct {
// The id of the record. If not specified it is inferred from the 'id' field of the record
Id string `json:"id"`
// record, JSON object
Record map[string]interface{} `json:"record"`
// Optional table name. Defaults to 'default'
Table string `json:"table"`
}
type UpdateResponse struct {
}

View File

@@ -1,41 +0,0 @@
package email
import (
"github.com/micro/micro-go/client"
)
func NewEmailService(token string) *EmailService {
return &EmailService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type EmailService struct {
client *client.Client
}
// Send an email by passing in from, to, subject, and a text or html body
func (t *EmailService) Send(request *SendRequest) (*SendResponse, error) {
rsp := &SendResponse{}
return rsp, t.client.Call("email", "Send", request, rsp)
}
type SendRequest struct {
// the display name of the sender
From string `json:"from"`
// the html body
HtmlBody string `json:"htmlBody"`
// an optional reply to email address
ReplyTo string `json:"replyTo"`
// the email subject
Subject string `json:"subject"`
// the text body
TextBody string `json:"textBody"`
// the email address of the recipient
To string `json:"to"`
}
type SendResponse struct {
}

View File

@@ -1,86 +0,0 @@
package emoji
import (
"github.com/micro/micro-go/client"
)
func NewEmojiService(token string) *EmojiService {
return &EmojiService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type EmojiService struct {
client *client.Client
}
// Find an emoji by its alias e.g :beer:
func (t *EmojiService) Find(request *FindRequest) (*FindResponse, error) {
rsp := &FindResponse{}
return rsp, t.client.Call("emoji", "Find", request, rsp)
}
// Get the flag for a country. Requires country code e.g GB for great britain
func (t *EmojiService) Flag(request *FlagRequest) (*FlagResponse, error) {
rsp := &FlagResponse{}
return rsp, t.client.Call("emoji", "Flag", request, rsp)
}
// Print text and renders the emojis with aliases e.g
// let's grab a :beer: becomes let's grab a 🍺
func (t *EmojiService) Print(request *PrintRequest) (*PrintResponse, error) {
rsp := &PrintResponse{}
return rsp, t.client.Call("emoji", "Print", request, rsp)
}
// Send an emoji to anyone via SMS. Messages are sent in the form '<message> Sent from <from>'
func (t *EmojiService) Send(request *SendRequest) (*SendResponse, error) {
rsp := &SendResponse{}
return rsp, t.client.Call("emoji", "Send", request, rsp)
}
type FindRequest struct {
// the alias code e.g :beer:
Alias string `json:"alias"`
}
type FindResponse struct {
// the unicode emoji 🍺
Emoji string `json:"emoji"`
}
type FlagRequest struct {
// country code e.g GB
Code string `json:"code"`
}
type FlagResponse struct {
// the emoji flag
Flag string `json:"flag"`
}
type PrintRequest struct {
// text including any alias e.g let's grab a :beer:
Text string `json:"text"`
}
type PrintResponse struct {
// text with rendered emojis
Text string `json:"text"`
}
type SendRequest struct {
// the name of the sender from e.g Alice
From string `json:"from"`
// message to send including emoji aliases
Message string `json:"message"`
// phone number to send to (including international dialing code)
To string `json:"to"`
}
type SendResponse struct {
// whether or not it succeeded
Success bool `json:"success"`
}

View File

@@ -1,240 +0,0 @@
package evchargers
import (
"github.com/micro/micro-go/client"
)
func NewEvchargersService(token string) *EvchargersService {
return &EvchargersService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type EvchargersService struct {
client *client.Client
}
// Retrieve reference data as used by this API and in conjunction with the Search endpoint
func (t *EvchargersService) ReferenceData(request *ReferenceDataRequest) (*ReferenceDataResponse, error) {
rsp := &ReferenceDataResponse{}
return rsp, t.client.Call("evchargers", "ReferenceData", request, rsp)
}
// Search by giving a coordinate and a max distance, or bounding box and optional filters
func (t *EvchargersService) Search(request *SearchRequest) (*SearchResponse, error) {
rsp := &SearchResponse{}
return rsp, t.client.Call("evchargers", "Search", request, rsp)
}
type Address struct {
// Any comments about how to access the charger
AccessComments string `json:"accessComments"`
AddressLine1 string `json:"addressLine1"`
AddressLine2 string `json:"addressLine2"`
Country *Country `json:"country"`
CountryId string `json:"countryId"`
LatLng string `json:"latLng"`
Location *Coordinates `json:"location"`
Postcode string `json:"postcode"`
StateOrProvince string `json:"stateOrProvince"`
Title string `json:"title"`
Town string `json:"town"`
}
type BoundingBox struct {
BottomLeft *Coordinates `json:"bottomLeft"`
TopRight *Coordinates `json:"topRight"`
}
type ChargerType struct {
Comments string `json:"comments"`
Id string `json:"id"`
// Is this 40KW+
IsFastChargeCapable bool `json:"isFastChargeCapable"`
Title string `json:"title"`
}
type CheckinStatusType struct {
Id string `json:"id"`
IsAutomated bool `json:"isAutomated"`
IsPositive bool `json:"isPositive"`
Title string `json:"title"`
}
type Connection struct {
// The amps offered
Amps float64 `json:"amps"`
ConnectionType *ConnectionType `json:"connectionType"`
// The ID of the connection type
ConnectionTypeId string `json:"connectionTypeId"`
// The current
Current string `json:"current"`
Level *ChargerType `json:"level"`
// The level of charging power available
LevelId string `json:"levelId"`
// The power in KW
Power float64 `json:"power"`
Reference string `json:"reference"`
// The voltage offered
Voltage float64 `json:"voltage"`
}
type ConnectionType struct {
FormalName string `json:"formalName"`
Id string `json:"id"`
IsDiscontinued bool `json:"isDiscontinued"`
IsObsolete bool `json:"isObsolete"`
Title string `json:"title"`
}
type Coordinates struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
}
type Country struct {
ContinentCode string `json:"continentCode"`
Id string `json:"id"`
IsoCode string `json:"isoCode"`
Title string `json:"title"`
}
type CurrentType struct {
Description string `json:"description"`
Id string `json:"id"`
Title string `json:"title"`
}
type DataProvider struct {
Comments string `json:"comments"`
DataProviderStatusType *DataProviderStatusType `json:"dataProviderStatusType"`
Id string `json:"id"`
// How is this data licensed
License string `json:"license"`
Title string `json:"title"`
Website string `json:"website"`
}
type DataProviderStatusType struct {
Id string `json:"id"`
IsProviderEnabled bool `json:"isProviderEnabled"`
Title string `json:"title"`
}
type Operator struct {
Comments string `json:"comments"`
ContactEmail string `json:"contactEmail"`
FaultReportEmail string `json:"faultReportEmail"`
Id string `json:"id"`
// Is this operator a private individual vs a company
IsPrivateIndividual bool `json:"isPrivateIndividual"`
PhonePrimary string `json:"phonePrimary"`
PhoneSecondary string `json:"phoneSecondary"`
Title string `json:"title"`
Website string `json:"website"`
}
type Poi struct {
// The address
Address *Address `json:"address"`
// The connections available at this charge point
Connections []Connection `json:"connections"`
// The cost of charging
Cost string `json:"cost"`
// The ID of the data provider
DataProviderId string `json:"dataProviderId"`
// The ID of the charger
Id string `json:"id"`
// The number of charging points
NumPoints int64 `json:"numPoints,string"`
// The operator
Operator *Operator `json:"operator"`
// The ID of the operator of the charger
OperatorId string `json:"operatorId"`
// The type of usage
UsageType *UsageType `json:"usageType"`
// The type of usage for this charger point (is it public, membership required, etc)
UsageTypeId string `json:"usageTypeId"`
}
type ReferenceDataRequest struct {
}
type ReferenceDataResponse struct {
// The types of charger
ChargerTypes *ChargerType `json:"chargerTypes"`
// The types of checkin status
CheckinStatusTypes *CheckinStatusType `json:"checkinStatusTypes"`
// The types of connection
ConnectionTypes *ConnectionType `json:"connectionTypes"`
// The countries
Countries []Country `json:"countries"`
// The types of current
CurrentTypes *CurrentType `json:"currentTypes"`
// The providers of the charger data
DataProviders *DataProvider `json:"dataProviders"`
// The companies operating the chargers
Operators []Operator `json:"operators"`
// The status of the charger
StatusTypes *StatusType `json:"statusTypes"`
// The status of a submission
SubmissionStatusTypes *SubmissionStatusType `json:"submissionStatusTypes"`
// The different types of usage
UsageTypes *UsageType `json:"usageTypes"`
// The types of user comment
UserCommentTypes *UserCommentType `json:"userCommentTypes"`
}
type SearchRequest struct {
// Bounding box to search within (top left and bottom right coordinates)
Box *BoundingBox `json:"box"`
// IDs of the connection type
ConnectionTypes string `json:"connectionTypes"`
// Country ID
CountryId string `json:"countryId"`
// Search distance from point in metres, defaults to 5000m
Distance int64 `json:"distance,string"`
// Supported charging levels
Levels []string `json:"levels"`
// Coordinates from which to begin search
Location *Coordinates `json:"location"`
// Maximum number of results to return, defaults to 100
MaxResults int64 `json:"maxResults,string"`
// Minimum power in KW. Note: data not available for many chargers
MinPower int64 `json:"minPower,string"`
// IDs of the the EV charger operator
Operators []string `json:"operators"`
// Usage of the charge point (is it public, membership required, etc)
UsageTypes string `json:"usageTypes"`
}
type SearchResponse struct {
Pois []Poi `json:"pois"`
}
type StatusType struct {
Id string `json:"id"`
IsOperational bool `json:"isOperational"`
Title string `json:"title"`
}
type SubmissionStatusType struct {
Id string `json:"id"`
IsLive bool `json:"isLive"`
Title string `json:"title"`
}
type UsageType struct {
Id string `json:"id"`
IsAccessKeyRequired bool `json:"isAccessKeyRequired"`
IsMembershipRequired bool `json:"isMembershipRequired"`
IsPayAtLocation bool `json:"isPayAtLocation"`
Title string `json:"title"`
}
type UserCommentType struct {
Id string `json:"id"`
Title string `json:"title"`
}

View File

@@ -1,88 +0,0 @@
package event
import (
"github.com/micro/micro-go/client"
)
func NewEventService(token string) *EventService {
return &EventService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type EventService struct {
client *client.Client
}
// Consume events from a given topic.
func (t *EventService) Consume(request *ConsumeRequest) (*ConsumeResponse, error) {
rsp := &ConsumeResponse{}
return rsp, t.client.Call("event", "Consume", request, rsp)
}
// Publish a event to the event stream.
func (t *EventService) Publish(request *PublishRequest) (*PublishResponse, error) {
rsp := &PublishResponse{}
return rsp, t.client.Call("event", "Publish", request, rsp)
}
// Read stored events
func (t *EventService) Read(request *ReadRequest) (*ReadResponse, error) {
rsp := &ReadResponse{}
return rsp, t.client.Call("event", "Read", request, rsp)
}
type ConsumeRequest struct {
// Optional group for the subscription
Group string `json:"group"`
// Optional offset to read from e.g "2006-01-02T15:04:05.999Z07:00"
Offset string `json:"offset"`
// The topic to subscribe to
Topic string `json:"topic"`
}
type ConsumeResponse struct {
// Unique message id
Id string `json:"id"`
// The next json message on the topic
Message map[string]interface{} `json:"message"`
// Timestamp of publishing
Timestamp string `json:"timestamp"`
// The topic subscribed to
Topic string `json:"topic"`
}
type Ev struct {
// event id
Id string `json:"id"`
// event message
Message map[string]interface{} `json:"message"`
// event timestamp
Timestamp string `json:"timestamp"`
}
type PublishRequest struct {
// The json message to publish
Message map[string]interface{} `json:"message"`
// The topic to publish to
Topic string `json:"topic"`
}
type PublishResponse struct {
}
type ReadRequest struct {
// number of events to read; default 25
Limit int32 `json:"limit"`
// offset for the events; default 0
Offset int32 `json:"offset"`
// topic to read from
Topic string `json:"topic"`
}
type ReadResponse struct {
// the events
Events []Ev `json:"events"`
}

View File

@@ -1,107 +0,0 @@
package file
import (
"github.com/micro/micro-go/client"
)
func NewFileService(token string) *FileService {
return &FileService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type FileService struct {
client *client.Client
}
// Delete a file by project name/path
func (t *FileService) Delete(request *DeleteRequest) (*DeleteResponse, error) {
rsp := &DeleteResponse{}
return rsp, t.client.Call("file", "Delete", request, rsp)
}
// List files by their project and optionally a path.
func (t *FileService) List(request *ListRequest) (*ListResponse, error) {
rsp := &ListResponse{}
return rsp, t.client.Call("file", "List", request, rsp)
}
// Read a file by path
func (t *FileService) Read(request *ReadRequest) (*ReadResponse, error) {
rsp := &ReadResponse{}
return rsp, t.client.Call("file", "Read", request, rsp)
}
// Save a file
func (t *FileService) Save(request *SaveRequest) (*SaveResponse, error) {
rsp := &SaveResponse{}
return rsp, t.client.Call("file", "Save", request, rsp)
}
type BatchSaveRequest struct {
Files []Record `json:"files"`
}
type BatchSaveResponse struct {
}
type DeleteRequest struct {
// Path to the file
Path string `json:"path"`
// The project name
Project string `json:"project"`
}
type DeleteResponse struct {
}
type ListRequest struct {
// Defaults to '/', ie. lists all files in a project.
// Supply path to a folder if you want to list
// files inside that folder
// eg. '/docs'
Path string `json:"path"`
// Project, required for listing.
Project string `json:"project"`
}
type ListResponse struct {
Files []Record `json:"files"`
}
type ReadRequest struct {
// Path to the file
Path string `json:"path"`
// Project name
Project string `json:"project"`
}
type ReadResponse struct {
// Returns the file
File *Record `json:"file"`
}
type Record struct {
// File contents
Content string `json:"content"`
// Time the file was created e.g 2021-05-20T13:37:21Z
Created string `json:"created"`
// Any other associated metadata as a map of key-value pairs
Metadata map[string]string `json:"metadata"`
// Path to file or folder eg. '/documents/text-files/file.txt'.
Path string `json:"path"`
// A custom project to group files
// eg. file-of-mywebsite.com
Project string `json:"project"`
// Time the file was updated e.g 2021-05-20T13:37:21Z
Updated string `json:"updated"`
}
type SaveRequest struct {
File *Record `json:"file"`
}
type SaveResponse struct {
}

View File

@@ -1,85 +0,0 @@
package forex
import (
"github.com/micro/micro-go/client"
)
func NewForexService(token string) *ForexService {
return &ForexService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type ForexService struct {
client *client.Client
}
// Returns the data for the previous close
func (t *ForexService) History(request *HistoryRequest) (*HistoryResponse, error) {
rsp := &HistoryResponse{}
return rsp, t.client.Call("forex", "History", request, rsp)
}
// Get the latest price for a given forex ticker
func (t *ForexService) Price(request *PriceRequest) (*PriceResponse, error) {
rsp := &PriceResponse{}
return rsp, t.client.Call("forex", "Price", request, rsp)
}
// Get the latest quote for the forex
func (t *ForexService) Quote(request *QuoteRequest) (*QuoteResponse, error) {
rsp := &QuoteResponse{}
return rsp, t.client.Call("forex", "Quote", request, rsp)
}
type HistoryRequest struct {
// the forex symbol e.g GBPUSD
Symbol string `json:"symbol"`
}
type HistoryResponse struct {
// the close price
Close float64 `json:"close"`
// the date
Date string `json:"date"`
// the peak price
High float64 `json:"high"`
// the low price
Low float64 `json:"low"`
// the open price
Open float64 `json:"open"`
// the forex symbol
Symbol string `json:"symbol"`
// the volume
Volume float64 `json:"volume"`
}
type PriceRequest struct {
// forex symbol e.g GBPUSD
Symbol string `json:"symbol"`
}
type PriceResponse struct {
// the last price
Price float64 `json:"price"`
// the forex symbol e.g GBPUSD
Symbol string `json:"symbol"`
}
type QuoteRequest struct {
// the forex symbol e.g GBPUSD
Symbol string `json:"symbol"`
}
type QuoteResponse struct {
// the asking price
AskPrice float64 `json:"askPrice"`
// the bidding price
BidPrice float64 `json:"bidPrice"`
// the forex symbol
Symbol string `json:"symbol"`
// the UTC timestamp of the quote
Timestamp string `json:"timestamp"`
}

View File

@@ -1,151 +0,0 @@
package function
import (
"github.com/micro/micro-go/client"
)
func NewFunctionService(token string) *FunctionService {
return &FunctionService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type FunctionService struct {
client *client.Client
}
// Call a function by name
func (t *FunctionService) Call(request *CallRequest) (*CallResponse, error) {
rsp := &CallResponse{}
return rsp, t.client.Call("function", "Call", request, rsp)
}
// Delete a function by name
func (t *FunctionService) Delete(request *DeleteRequest) (*DeleteResponse, error) {
rsp := &DeleteResponse{}
return rsp, t.client.Call("function", "Delete", request, rsp)
}
// Deploy a group of functions
func (t *FunctionService) Deploy(request *DeployRequest) (*DeployResponse, error) {
rsp := &DeployResponse{}
return rsp, t.client.Call("function", "Deploy", request, rsp)
}
// Get the info for a deployed function
func (t *FunctionService) Describe(request *DescribeRequest) (*DescribeResponse, error) {
rsp := &DescribeResponse{}
return rsp, t.client.Call("function", "Describe", request, rsp)
}
// List all the deployed functions
func (t *FunctionService) List(request *ListRequest) (*ListResponse, error) {
rsp := &ListResponse{}
return rsp, t.client.Call("function", "List", request, rsp)
}
type CallRequest struct {
// Name of the function
Name string `json:"name"`
// Request body that will be passed to the function
Request map[string]interface{} `json:"request"`
}
type CallResponse struct {
// Response body that the function returned
Response map[string]interface{} `json:"response"`
}
type DeleteRequest struct {
// The name of the function
Name string `json:"name"`
// Optional project name
Project string `json:"project"`
}
type DeleteResponse struct {
}
type DeployRequest struct {
// entry point, ie. handler name in the source code
// if not provided, defaults to the name parameter
Entrypoint string `json:"entrypoint"`
// environment variables to pass in at runtime
EnvVars map[string]string `json:"envVars"`
// function name
Name string `json:"name"`
// project is used for namespacing your functions
// optional. defaults to "default".
Project string `json:"project"`
// github url to repo
Repo string `json:"repo"`
// runtime/language of the function
// eg: php74,
// nodejs6, nodejs8, nodejs10, nodejs12, nodejs14, nodejs16
// dotnet3
// java11
// ruby26, ruby27
// go111, go113, go116
// python37, python38, python39
Runtime string `json:"runtime"`
// optional subfolder path
Subfolder string `json:"subfolder"`
}
type DeployResponse struct {
}
type DescribeRequest struct {
// The name of the function
Name string `json:"name"`
// Optional project name
Project string `json:"project"`
}
type DescribeResponse struct {
// The function requested
Function *Func `json:"function"`
// The timeout for requests to the function
Timeout string `json:"timeout"`
// The time at which the function was updated
UpdatedAt string `json:"updatedAt"`
}
type Func struct {
// name of handler in source code
Entrypoint string `json:"entrypoint"`
// function name
// limitation: must be unique across projects
Name string `json:"name"`
// project of function, optional
// defaults to literal "default"
// used to namespace functions
Project string `json:"project"`
// git repo address
Repo string `json:"repo"`
// runtime/language of the function
// eg: php74,
// nodejs6, nodejs8, nodejs10, nodejs12, nodejs14, nodejs16
// dotnet3
// java11
// ruby26, ruby27
// go111, go113, go116
// python37, python38, python39
Runtime string `json:"runtime"`
// eg. ACTIVE, DEPLOY_IN_PROGRESS, OFFLINE etc
Status string `json:"status"`
// subfolder path to entrypoint
Subfolder string `json:"subfolder"`
}
type ListRequest struct {
// optional project name
Project string `json:"project"`
}
type ListResponse struct {
// List of functions deployed
Functions []Func `json:"functions"`
}

View File

@@ -1,64 +0,0 @@
package geocoding
import (
"github.com/micro/micro-go/client"
)
func NewGeocodingService(token string) *GeocodingService {
return &GeocodingService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type GeocodingService struct {
client *client.Client
}
// Lookup returns a geocoded address including normalized address and gps coordinates. All fields are optional, provide more to get more accurate results
func (t *GeocodingService) Lookup(request *LookupRequest) (*LookupResponse, error) {
rsp := &LookupResponse{}
return rsp, t.client.Call("geocoding", "Lookup", request, rsp)
}
// Reverse lookup an address from gps coordinates
func (t *GeocodingService) Reverse(request *ReverseRequest) (*ReverseResponse, error) {
rsp := &ReverseResponse{}
return rsp, t.client.Call("geocoding", "Reverse", request, rsp)
}
type Address struct {
City string `json:"city"`
Country string `json:"country"`
LineOne string `json:"lineOne"`
LineTwo string `json:"lineTwo"`
Postcode string `json:"postcode"`
}
type Location struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
}
type LookupRequest struct {
Address string `json:"address"`
City string `json:"city"`
Country string `json:"country"`
Postcode string `json:"postcode"`
}
type LookupResponse struct {
Address *Address `json:"address"`
Location *Location `json:"location"`
}
type ReverseRequest struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
}
type ReverseResponse struct {
Address *Address `json:"address"`
Location *Location `json:"location"`
}

View File

@@ -1,135 +0,0 @@
package gifs
import (
"github.com/micro/micro-go/client"
)
func NewGifsService(token string) *GifsService {
return &GifsService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type GifsService struct {
client *client.Client
}
// Search for a GIF
func (t *GifsService) Search(request *SearchRequest) (*SearchResponse, error) {
rsp := &SearchResponse{}
return rsp, t.client.Call("gifs", "Search", request, rsp)
}
type Gif struct {
// URL used for embedding the GIF
EmbedUrl string `json:"embedUrl"`
// The ID of the GIF
Id string `json:"id"`
// The different formats available for this GIF
Images *ImageFormats `json:"images"`
// The content rating for the GIF
Rating string `json:"rating"`
// A short URL for this GIF
ShortUrl string `json:"shortUrl"`
// The slug used in the GIF's URL
Slug string `json:"slug"`
// The page on which this GIF was found
Source string `json:"source"`
// The title for this GIF
Title string `json:"title"`
// The URL for this GIF
Url string `json:"url"`
}
type ImageFormat struct {
// height
Height int32 `json:"height"`
// size of the MP4 version
Mp4size int32 `json:"mp4size"`
// URL to an MP4 version of the gif
Mp4url string `json:"mp4url"`
// size in bytes
Size int32 `json:"size"`
// URL of the gif
Url string `json:"url"`
// size of the webp version
WebpSize int32 `json:"webpSize"`
// URL to a webp version of the gif
WebpUrl string `json:"webpUrl"`
// width
Width int32 `json:"width"`
}
type ImageFormats struct {
// A downsized version of the GIF < 2MB
Downsized *ImageFormat `json:"downsized"`
// A downsized version of the GIF < 8MB
DownsizedLarge *ImageFormat `json:"downsizedLarge"`
// A downsized version of the GIF < 5MB
DownsizedMedium *ImageFormat `json:"downsizedMedium"`
// A downsized version of the GIF < 200kb
DownsizedSmall *ImageFormat `json:"downsizedSmall"`
// Static image of the downsized version of the GIF
DownsizedStill *ImageFormat `json:"downsizedStill"`
// Version of the GIF with fixed height of 200 pixels. Good for mobile use
FixedHeight *ImageFormat `json:"fixedHeight"`
// Version of the GIF with fixed height of 200 pixels and number of frames reduced to 6
FixedHeightDownsampled *ImageFormat `json:"fixedHeightDownsampled"`
// Version of the GIF with fixed height of 100 pixels. Good for mobile keyboards
FixedHeightSmall *ImageFormat `json:"fixedHeightSmall"`
// Static image of the GIF with fixed height of 100 pixels
FixedHeightSmallStill *ImageFormat `json:"fixedHeightSmallStill"`
// Static image of the GIF with fixed height of 200 pixels
FixedHeightStill *ImageFormat `json:"fixedHeightStill"`
// Version of the GIF with fixed width of 200 pixels. Good for mobile use
FixedWidth *ImageFormat `json:"fixedWidth"`
// Version of the GIF with fixed width of 200 pixels and number of frames reduced to 6
FixedWidthDownsampled *ImageFormat `json:"fixedWidthDownsampled"`
// Version of the GIF with fixed width of 100 pixels. Good for mobile keyboards
FixedWidthSmall *ImageFormat `json:"fixedWidthSmall"`
// Static image of the GIF with fixed width of 100 pixels
FixedWidthSmallStill *ImageFormat `json:"fixedWidthSmallStill"`
// Static image of the GIF with fixed width of 200 pixels
FixedWidthStill *ImageFormat `json:"fixedWidthStill"`
// 15 second version of the GIF looping
Looping *ImageFormat `json:"looping"`
// The original GIF. Good for desktop use
Original *ImageFormat `json:"original"`
// Static image of the original version of the GIF
OriginalStill *ImageFormat `json:"originalStill"`
// mp4 version of the GIF <50kb displaying first 1-2 secs
Preview *ImageFormat `json:"preview"`
// Version of the GIF <50kb displaying first 1-2 secs
PreviewGif *ImageFormat `json:"previewGif"`
}
type Pagination struct {
// total number returned in this response
Count int32 `json:"count"`
// position in pagination
Offset int32 `json:"offset"`
// total number of results available
TotalCount int32 `json:"totalCount"`
}
type SearchRequest struct {
// ISO 2 letter language code for regional content
Lang string `json:"lang"`
// Max number of gifs to return. Defaults to 25
Limit int32 `json:"limit"`
// The start position of results (used with pagination)
Offset int32 `json:"offset"`
// The search term
Query string `json:"query"`
// Apply age related content filter. "g", "pg", "pg-13", or "r". Defaults to "g"
Rating string `json:"rating"`
}
type SearchResponse struct {
// list of results
Data []Gif `json:"data"`
// information on pagination
Pagination *Pagination `json:"pagination"`
}

View File

@@ -1,48 +0,0 @@
package google
import (
"github.com/micro/micro-go/client"
)
func NewGoogleService(token string) *GoogleService {
return &GoogleService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type GoogleService struct {
client *client.Client
}
// Search for videos on Google
func (t *GoogleService) Search(request *SearchRequest) (*SearchResponse, error) {
rsp := &SearchResponse{}
return rsp, t.client.Call("google", "Search", request, rsp)
}
type SearchRequest struct {
// Query to search for
Query string `json:"query"`
}
type SearchResponse struct {
// List of results for the query
Results []SearchResult `json:"results"`
}
type SearchResult struct {
// abridged version of this search results URL, e.g. www.exampe.com
DisplayUrl string `json:"displayUrl"`
// id of the result
Id string `json:"id"`
// kind of result; "search"
Kind string `json:"kind"`
// the result snippet
Snippet string `json:"snippet"`
// title of the result
Title string `json:"title"`
// the full url for the result
Url string `json:"url"`
}

View File

@@ -1,47 +0,0 @@
package helloworld
import (
"github.com/micro/micro-go/client"
)
func NewHelloworldService(token string) *HelloworldService {
return &HelloworldService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type HelloworldService struct {
client *client.Client
}
// Call returns a personalised "Hello $name" response
func (t *HelloworldService) Call(request *CallRequest) (*CallResponse, error) {
rsp := &CallResponse{}
return rsp, t.client.Call("helloworld", "Call", request, rsp)
}
// Stream returns a stream of "Hello $name" responses
func (t *HelloworldService) Stream(request *StreamRequest) (*StreamResponse, error) {
rsp := &StreamResponse{}
return rsp, t.client.Call("helloworld", "Stream", request, rsp)
}
type CallRequest struct {
Name string `json:"name"`
}
type CallResponse struct {
Message string `json:"message"`
}
type StreamRequest struct {
// the number of messages to send back
Messages int64 `json:"messages,string"`
Name string `json:"name"`
}
type StreamResponse struct {
Message string `json:"message"`
}

View File

@@ -1,69 +0,0 @@
package holidays
import (
"github.com/micro/micro-go/client"
)
func NewHolidaysService(token string) *HolidaysService {
return &HolidaysService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type HolidaysService struct {
client *client.Client
}
// Get the list of countries that are supported by this API
func (t *HolidaysService) Countries(request *CountriesRequest) (*CountriesResponse, error) {
rsp := &CountriesResponse{}
return rsp, t.client.Call("holidays", "Countries", request, rsp)
}
// List the holiday dates for a given country and year
func (t *HolidaysService) List(request *ListRequest) (*ListResponse, error) {
rsp := &ListResponse{}
return rsp, t.client.Call("holidays", "List", request, rsp)
}
type CountriesRequest struct {
}
type CountriesResponse struct {
Countries []Country `json:"countries"`
}
type Country struct {
// The 2 letter country code (as defined in ISO 3166-1 alpha-2)
Code string `json:"code"`
// The English name of the country
Name string `json:"name"`
}
type Holiday struct {
// the country this holiday occurs in
CountryCode string `json:"countryCode"`
// date of the holiday in yyyy-mm-dd format
Date string `json:"date"`
// the local name of the holiday
LocalName string `json:"localName"`
// the name of the holiday in English
Name string `json:"name"`
// the regions within the country that observe this holiday (if not all of them)
Regions []string `json:"regions"`
// the type of holiday Public, Bank, School, Authorities, Optional, Observance
Types []string `json:"types"`
}
type ListRequest struct {
// The 2 letter country code (as defined in ISO 3166-1 alpha-2)
CountryCode string `json:"countryCode"`
// The year to list holidays for
Year int64 `json:"year,string"`
}
type ListResponse struct {
Holidays []Holiday `json:"holidays"`
}

View File

@@ -1,48 +0,0 @@
package id
import (
"github.com/micro/micro-go/client"
)
func NewIdService(token string) *IdService {
return &IdService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type IdService struct {
client *client.Client
}
// Generate a unique ID. Defaults to uuid.
func (t *IdService) Generate(request *GenerateRequest) (*GenerateResponse, error) {
rsp := &GenerateResponse{}
return rsp, t.client.Call("id", "Generate", request, rsp)
}
// List the types of IDs available. No query params needed.
func (t *IdService) Types(request *TypesRequest) (*TypesResponse, error) {
rsp := &TypesResponse{}
return rsp, t.client.Call("id", "Types", request, rsp)
}
type GenerateRequest struct {
// type of id e.g uuid, shortid, snowflake (64 bit), bigflake (128 bit)
Type string `json:"type"`
}
type GenerateResponse struct {
// the unique id generated
Id string `json:"id"`
// the type of id generated
Type string `json:"type"`
}
type TypesRequest struct {
}
type TypesResponse struct {
Types []string `json:"types"`
}

View File

@@ -1,138 +0,0 @@
package image
import (
"github.com/micro/micro-go/client"
)
func NewImageService(token string) *ImageService {
return &ImageService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type ImageService struct {
client *client.Client
}
// Convert an image from one format (jpeg, png etc.) to an other either on the fly (from base64 to base64),
// or by uploading the conversion result.
// To use the file parameter you need to send the request as a multipart/form-data rather than the usual application/json
// with each parameter as a form field.
func (t *ImageService) Convert(request *ConvertRequest) (*ConvertResponse, error) {
rsp := &ConvertResponse{}
return rsp, t.client.Call("image", "Convert", request, rsp)
}
// Delete an image previously uploaded.
func (t *ImageService) Delete(request *DeleteRequest) (*DeleteResponse, error) {
rsp := &DeleteResponse{}
return rsp, t.client.Call("image", "Delete", request, rsp)
}
// Resize an image on the fly without storing it (by sending and receiving a base64 encoded image), or resize and upload depending on parameters.
// If one of width or height is 0, the image aspect ratio is preserved.
// Optional cropping.
// To use the file parameter you need to send the request as a multipart/form-data rather than the usual application/json
// with each parameter as a form field.
func (t *ImageService) Resize(request *ResizeRequest) (*ResizeResponse, error) {
rsp := &ResizeResponse{}
return rsp, t.client.Call("image", "Resize", request, rsp)
}
// Upload an image by either sending a base64 encoded image to this endpoint or a URL.
// To resize an image before uploading, see the Resize endpoint.
// To use the file parameter you need to send the request as a multipart/form-data rather than the usual application/json
// with each parameter as a form field.
func (t *ImageService) Upload(request *UploadRequest) (*UploadResponse, error) {
rsp := &UploadResponse{}
return rsp, t.client.Call("image", "Upload", request, rsp)
}
type ConvertRequest struct {
// base64 encoded image to resize,
Base64 string `json:"base64"`
// The image file to convert
File string `json:"file"`
// output name of the image including extension, ie. "cat.png"
Name string `json:"name"`
// make output a URL and not a base64 response
OutputUrl bool `json:"outputUrl"`
// url of the image to resize
Url string `json:"url"`
}
type ConvertResponse struct {
Base64 string `json:"base64"`
Url string `json:"url"`
}
type CropOptions struct {
// Crop anchor point: "top", "top left", "top right",
// "left", "center", "right"
// "bottom left", "bottom", "bottom right".
// Optional. Defaults to center.
Anchor string `json:"anchor"`
// height to crop to
Height int32 `json:"height"`
// width to crop to
Width int32 `json:"width"`
}
type DeleteRequest struct {
// url of the image to delete e.g. https://cdn.m3ocontent.com/micro/images/micro/41e23b39-48dd-42b6-9738-79a313414bb8/cat.jpeg
Url string `json:"url"`
}
type DeleteResponse struct {
}
type Point struct {
X int32 `json:"x"`
Y int32 `json:"y"`
}
type Rectangle struct {
Max *Point `json:"max"`
Min *Point `json:"min"`
}
type ResizeRequest struct {
// base64 encoded image to resize,
Base64 string `json:"base64"`
// optional crop options
// if provided, after resize, the image
// will be cropped
CropOptions *CropOptions `json:"cropOptions"`
// The image file to resize
File string `json:"file"`
Height int64 `json:"height,string"`
// output name of the image including extension, ie. "cat.png"
Name string `json:"name"`
// make output a URL and not a base64 response
OutputUrl bool `json:"outputUrl"`
// url of the image to resize
Url string `json:"url"`
Width int64 `json:"width,string"`
}
type ResizeResponse struct {
Base64 string `json:"base64"`
Url string `json:"url"`
}
type UploadRequest struct {
// Base64 encoded image to upload,
Base64 string `json:"base64"`
// The image file to upload
File string `json:"file"`
// Output name of the image including extension, ie. "cat.png"
Name string `json:"name"`
// URL of the image to upload
Url string `json:"url"`
}
type UploadResponse struct {
Url string `json:"url"`
}

View File

@@ -1,47 +0,0 @@
package ip
import (
"github.com/micro/micro-go/client"
)
func NewIpService(token string) *IpService {
return &IpService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type IpService struct {
client *client.Client
}
// Lookup the geolocation information for an IP address
func (t *IpService) Lookup(request *LookupRequest) (*LookupResponse, error) {
rsp := &LookupResponse{}
return rsp, t.client.Call("ip", "Lookup", request, rsp)
}
type LookupRequest struct {
// IP to lookup
Ip string `json:"ip"`
}
type LookupResponse struct {
// Autonomous system number
Asn int32 `json:"asn"`
// Name of the city
City string `json:"city"`
// Name of the continent
Continent string `json:"continent"`
// Name of the country
Country string `json:"country"`
// IP of the query
Ip string `json:"ip"`
// Latitude e.g 52.523219
Latitude float64 `json:"latitude"`
// Longitude e.g 13.428555
Longitude float64 `json:"longitude"`
// Timezone e.g Europe/Rome
Timezone string `json:"timezone"`
}

View File

@@ -1,78 +0,0 @@
package location
import (
"github.com/micro/micro-go/client"
)
func NewLocationService(token string) *LocationService {
return &LocationService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type LocationService struct {
client *client.Client
}
// Read an entity by its ID
func (t *LocationService) Read(request *ReadRequest) (*ReadResponse, error) {
rsp := &ReadResponse{}
return rsp, t.client.Call("location", "Read", request, rsp)
}
// Save an entity's current position
func (t *LocationService) Save(request *SaveRequest) (*SaveResponse, error) {
rsp := &SaveResponse{}
return rsp, t.client.Call("location", "Save", request, rsp)
}
// Search for entities in a given radius
func (t *LocationService) Search(request *SearchRequest) (*SearchResponse, error) {
rsp := &SearchResponse{}
return rsp, t.client.Call("location", "Search", request, rsp)
}
type Entity struct {
Id string `json:"id"`
Location *Point `json:"location"`
Type string `json:"type"`
}
type Point struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Timestamp int64 `json:"timestamp,string"`
}
type ReadRequest struct {
// the entity id
Id string `json:"id"`
}
type ReadResponse struct {
Entity *Entity `json:"entity"`
}
type SaveRequest struct {
Entity *Entity `json:"entity"`
}
type SaveResponse struct {
}
type SearchRequest struct {
// Central position to search from
Center *Point `json:"center"`
// Maximum number of entities to return
NumEntities int64 `json:"numEntities,string"`
// radius in meters
Radius float64 `json:"radius"`
// type of entities to filter
Type string `json:"type"`
}
type SearchResponse struct {
Entities []Entity `json:"entities"`
}

View File

@@ -1,151 +0,0 @@
package services
import (
"github.com/micro/services/clients/go/address"
"github.com/micro/services/clients/go/answer"
"github.com/micro/services/clients/go/cache"
"github.com/micro/services/clients/go/crypto"
"github.com/micro/services/clients/go/currency"
"github.com/micro/services/clients/go/db"
"github.com/micro/services/clients/go/email"
"github.com/micro/services/clients/go/emoji"
"github.com/micro/services/clients/go/evchargers"
"github.com/micro/services/clients/go/event"
"github.com/micro/services/clients/go/file"
"github.com/micro/services/clients/go/forex"
"github.com/micro/services/clients/go/function"
"github.com/micro/services/clients/go/geocoding"
"github.com/micro/services/clients/go/gifs"
"github.com/micro/services/clients/go/google"
"github.com/micro/services/clients/go/helloworld"
"github.com/micro/services/clients/go/holidays"
"github.com/micro/services/clients/go/id"
"github.com/micro/services/clients/go/image"
"github.com/micro/services/clients/go/ip"
"github.com/micro/services/clients/go/location"
"github.com/micro/services/clients/go/mq"
"github.com/micro/services/clients/go/notes"
"github.com/micro/services/clients/go/otp"
"github.com/micro/services/clients/go/postcode"
"github.com/micro/services/clients/go/prayer"
"github.com/micro/services/clients/go/qr"
"github.com/micro/services/clients/go/quran"
"github.com/micro/services/clients/go/routing"
"github.com/micro/services/clients/go/rss"
"github.com/micro/services/clients/go/sentiment"
"github.com/micro/services/clients/go/sms"
"github.com/micro/services/clients/go/spam"
"github.com/micro/services/clients/go/stock"
"github.com/micro/services/clients/go/stream"
"github.com/micro/services/clients/go/sunnah"
"github.com/micro/services/clients/go/thumbnail"
"github.com/micro/services/clients/go/time"
"github.com/micro/services/clients/go/twitter"
"github.com/micro/services/clients/go/url"
"github.com/micro/services/clients/go/user"
"github.com/micro/services/clients/go/vehicle"
"github.com/micro/services/clients/go/weather"
"github.com/micro/services/clients/go/youtube"
)
func NewClient(token string) *Client {
return &Client{
token: token,
AddressService: address.NewAddressService(token),
AnswerService: answer.NewAnswerService(token),
CacheService: cache.NewCacheService(token),
CryptoService: crypto.NewCryptoService(token),
CurrencyService: currency.NewCurrencyService(token),
DbService: db.NewDbService(token),
EmailService: email.NewEmailService(token),
EmojiService: emoji.NewEmojiService(token),
EvchargersService: evchargers.NewEvchargersService(token),
EventService: event.NewEventService(token),
FileService: file.NewFileService(token),
ForexService: forex.NewForexService(token),
FunctionService: function.NewFunctionService(token),
GeocodingService: geocoding.NewGeocodingService(token),
GifsService: gifs.NewGifsService(token),
GoogleService: google.NewGoogleService(token),
HelloworldService: helloworld.NewHelloworldService(token),
HolidaysService: holidays.NewHolidaysService(token),
IdService: id.NewIdService(token),
ImageService: image.NewImageService(token),
IpService: ip.NewIpService(token),
LocationService: location.NewLocationService(token),
MqService: mq.NewMqService(token),
NotesService: notes.NewNotesService(token),
OtpService: otp.NewOtpService(token),
PostcodeService: postcode.NewPostcodeService(token),
PrayerService: prayer.NewPrayerService(token),
QrService: qr.NewQrService(token),
QuranService: quran.NewQuranService(token),
RoutingService: routing.NewRoutingService(token),
RssService: rss.NewRssService(token),
SentimentService: sentiment.NewSentimentService(token),
SmsService: sms.NewSmsService(token),
SpamService: spam.NewSpamService(token),
StockService: stock.NewStockService(token),
StreamService: stream.NewStreamService(token),
SunnahService: sunnah.NewSunnahService(token),
ThumbnailService: thumbnail.NewThumbnailService(token),
TimeService: time.NewTimeService(token),
TwitterService: twitter.NewTwitterService(token),
UrlService: url.NewUrlService(token),
UserService: user.NewUserService(token),
VehicleService: vehicle.NewVehicleService(token),
WeatherService: weather.NewWeatherService(token),
YoutubeService: youtube.NewYoutubeService(token),
}
}
type Client struct {
token string
AddressService *address.AddressService
AnswerService *answer.AnswerService
CacheService *cache.CacheService
CryptoService *crypto.CryptoService
CurrencyService *currency.CurrencyService
DbService *db.DbService
EmailService *email.EmailService
EmojiService *emoji.EmojiService
EvchargersService *evchargers.EvchargersService
EventService *event.EventService
FileService *file.FileService
ForexService *forex.ForexService
FunctionService *function.FunctionService
GeocodingService *geocoding.GeocodingService
GifsService *gifs.GifsService
GoogleService *google.GoogleService
HelloworldService *helloworld.HelloworldService
HolidaysService *holidays.HolidaysService
IdService *id.IdService
ImageService *image.ImageService
IpService *ip.IpService
LocationService *location.LocationService
MqService *mq.MqService
NotesService *notes.NotesService
OtpService *otp.OtpService
PostcodeService *postcode.PostcodeService
PrayerService *prayer.PrayerService
QrService *qr.QrService
QuranService *quran.QuranService
RoutingService *routing.RoutingService
RssService *rss.RssService
SentimentService *sentiment.SentimentService
SmsService *sms.SmsService
SpamService *spam.SpamService
StockService *stock.StockService
StreamService *stream.StreamService
SunnahService *sunnah.SunnahService
ThumbnailService *thumbnail.ThumbnailService
TimeService *time.TimeService
TwitterService *twitter.TwitterService
UrlService *url.UrlService
UserService *user.UserService
VehicleService *vehicle.VehicleService
WeatherService *weather.WeatherService
YoutubeService *youtube.YoutubeService
}

View File

@@ -1,51 +0,0 @@
package mq
import (
"github.com/micro/micro-go/client"
)
func NewMqService(token string) *MqService {
return &MqService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type MqService struct {
client *client.Client
}
// Publish a message. Specify a topic to group messages for a specific topic.
func (t *MqService) Publish(request *PublishRequest) (*PublishResponse, error) {
rsp := &PublishResponse{}
return rsp, t.client.Call("mq", "Publish", request, rsp)
}
// Subscribe to messages for a given topic.
func (t *MqService) Subscribe(request *SubscribeRequest) (*SubscribeResponse, error) {
rsp := &SubscribeResponse{}
return rsp, t.client.Call("mq", "Subscribe", request, rsp)
}
type PublishRequest struct {
// The json message to publish
Message map[string]interface{} `json:"message"`
// The topic to publish to
Topic string `json:"topic"`
}
type PublishResponse struct {
}
type SubscribeRequest struct {
// The topic to subscribe to
Topic string `json:"topic"`
}
type SubscribeResponse struct {
// The next json message on the topic
Message map[string]interface{} `json:"message"`
// The topic subscribed to
Topic string `json:"topic"`
}

View File

@@ -1,125 +0,0 @@
package notes
import (
"github.com/micro/micro-go/client"
)
func NewNotesService(token string) *NotesService {
return &NotesService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type NotesService struct {
client *client.Client
}
// Create a new note
func (t *NotesService) Create(request *CreateRequest) (*CreateResponse, error) {
rsp := &CreateResponse{}
return rsp, t.client.Call("notes", "Create", request, rsp)
}
// Delete a note
func (t *NotesService) Delete(request *DeleteRequest) (*DeleteResponse, error) {
rsp := &DeleteResponse{}
return rsp, t.client.Call("notes", "Delete", request, rsp)
}
// Subscribe to notes events
func (t *NotesService) Events(request *EventsRequest) (*EventsResponse, error) {
rsp := &EventsResponse{}
return rsp, t.client.Call("notes", "Events", request, rsp)
}
// List all the notes
func (t *NotesService) List(request *ListRequest) (*ListResponse, error) {
rsp := &ListResponse{}
return rsp, t.client.Call("notes", "List", request, rsp)
}
// Read a note
func (t *NotesService) Read(request *ReadRequest) (*ReadResponse, error) {
rsp := &ReadResponse{}
return rsp, t.client.Call("notes", "Read", request, rsp)
}
// Update a note
func (t *NotesService) Update(request *UpdateRequest) (*UpdateResponse, error) {
rsp := &UpdateResponse{}
return rsp, t.client.Call("notes", "Update", request, rsp)
}
type CreateRequest struct {
// note text
Text string `json:"text"`
// note title
Title string `json:"title"`
}
type CreateResponse struct {
// The created note
Note *Note `json:"note"`
}
type DeleteRequest struct {
// specify the id of the note
Id string `json:"id"`
}
type DeleteResponse struct {
Note *Note `json:"note"`
}
type EventsRequest struct {
// optionally specify a note id
Id string `json:"id"`
}
type EventsResponse struct {
// the event which occured; create, delete, update
Event string `json:"event"`
// the note which the operation occured on
Note *Note `json:"note"`
}
type ListRequest struct {
}
type ListResponse struct {
// the list of notes
Notes []Note `json:"notes"`
}
type Note struct {
// time at which the note was created
Created string `json:"created"`
// unique id for the note, generated if not specified
Id string `json:"id"`
// text within the note
Text string `json:"text"`
// title of the note
Title string `json:"title"`
// time at which the note was updated
Updated string `json:"updated"`
}
type ReadRequest struct {
// the note id
Id string `json:"id"`
}
type ReadResponse struct {
// The note
Note *Note `json:"note"`
}
type UpdateRequest struct {
Note *Note `json:"note"`
}
type UpdateResponse struct {
Note *Note `json:"note"`
}

View File

@@ -1,55 +0,0 @@
package otp
import (
"github.com/micro/micro-go/client"
)
func NewOtpService(token string) *OtpService {
return &OtpService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type OtpService struct {
client *client.Client
}
// Generate an OTP (one time pass) code
func (t *OtpService) Generate(request *GenerateRequest) (*GenerateResponse, error) {
rsp := &GenerateResponse{}
return rsp, t.client.Call("otp", "Generate", request, rsp)
}
// Validate the OTP code
func (t *OtpService) Validate(request *ValidateRequest) (*ValidateResponse, error) {
rsp := &ValidateResponse{}
return rsp, t.client.Call("otp", "Validate", request, rsp)
}
type GenerateRequest struct {
// expiration in seconds (default: 60)
Expiry int64 `json:"expiry,string"`
// unique id, email or user to generate an OTP for
Id string `json:"id"`
// number of characters (default: 6)
Size int64 `json:"size,string"`
}
type GenerateResponse struct {
// one time pass code
Code string `json:"code"`
}
type ValidateRequest struct {
// one time pass code to validate
Code string `json:"code"`
// unique id, email or user for which the code was generated
Id string `json:"id"`
}
type ValidateResponse struct {
// returns true if the code is valid for the ID
Success bool `json:"success"`
}

View File

@@ -1,87 +0,0 @@
package postcode
import (
"github.com/micro/micro-go/client"
)
func NewPostcodeService(token string) *PostcodeService {
return &PostcodeService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type PostcodeService struct {
client *client.Client
}
// Lookup a postcode to retrieve the related region, county, etc
func (t *PostcodeService) Lookup(request *LookupRequest) (*LookupResponse, error) {
rsp := &LookupResponse{}
return rsp, t.client.Call("postcode", "Lookup", request, rsp)
}
// Return a random postcode and its related info
func (t *PostcodeService) Random(request *RandomRequest) (*RandomResponse, error) {
rsp := &RandomResponse{}
return rsp, t.client.Call("postcode", "Random", request, rsp)
}
// Validate a postcode.
func (t *PostcodeService) Validate(request *ValidateRequest) (*ValidateResponse, error) {
rsp := &ValidateResponse{}
return rsp, t.client.Call("postcode", "Validate", request, rsp)
}
type LookupRequest struct {
// UK postcode e.g SW1A 2AA
Postcode string `json:"postcode"`
}
type LookupResponse struct {
// country e.g United Kingdom
Country string `json:"country"`
// e.g Westminster
District string `json:"district"`
// e.g 51.50354
Latitude float64 `json:"latitude"`
// e.g -0.127695
Longitude float64 `json:"longitude"`
// UK postcode e.g SW1A 2AA
Postcode string `json:"postcode"`
// related region e.g London
Region string `json:"region"`
// e.g St James's
Ward string `json:"ward"`
}
type RandomRequest struct {
}
type RandomResponse struct {
// country e.g United Kingdom
Country string `json:"country"`
// e.g Westminster
District string `json:"district"`
// e.g 51.50354
Latitude float64 `json:"latitude"`
// e.g -0.127695
Longitude float64 `json:"longitude"`
// UK postcode e.g SW1A 2AA
Postcode string `json:"postcode"`
// related region e.g London
Region string `json:"region"`
// e.g St James's
Ward string `json:"ward"`
}
type ValidateRequest struct {
// UK postcode e.g SW1A 2AA
Postcode string `json:"postcode"`
}
type ValidateResponse struct {
// Is the postcode valid (true) or not (false)
Valid bool `json:"valid"`
}

View File

@@ -1,69 +0,0 @@
package prayer
import (
"github.com/micro/micro-go/client"
)
func NewPrayerService(token string) *PrayerService {
return &PrayerService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type PrayerService struct {
client *client.Client
}
// Get the prayer (salah) times for a location on a given date
func (t *PrayerService) Times(request *TimesRequest) (*TimesResponse, error) {
rsp := &TimesResponse{}
return rsp, t.client.Call("prayer", "Times", request, rsp)
}
type PrayerTime struct {
// asr time
Asr string `json:"asr"`
// date for prayer times in YYYY-MM-DD format
Date string `json:"date"`
// fajr time
Fajr string `json:"fajr"`
// isha time
Isha string `json:"isha"`
// maghrib time
Maghrib string `json:"maghrib"`
// time of sunrise
Sunrise string `json:"sunrise"`
// zuhr time
Zuhr string `json:"zuhr"`
}
type TimesRequest struct {
// optional date in YYYY-MM-DD format, otherwise uses today
Date string `json:"date"`
// number of days to request times for
Days int32 `json:"days"`
// optional latitude used in place of location
Latitude float64 `json:"latitude"`
// location to retrieve prayer times for.
// this can be a specific address, city, etc
Location string `json:"location"`
// optional longitude used in place of location
Longitude float64 `json:"longitude"`
}
type TimesResponse struct {
// date of request
Date string `json:"date"`
// number of days
Days int32 `json:"days"`
// latitude of location
Latitude float64 `json:"latitude"`
// location for the request
Location string `json:"location"`
// longitude of location
Longitude float64 `json:"longitude"`
// prayer times for the given location
Times []PrayerTime `json:"times"`
}

View File

@@ -1,35 +0,0 @@
package qr
import (
"github.com/micro/micro-go/client"
)
func NewQrService(token string) *QrService {
return &QrService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type QrService struct {
client *client.Client
}
// Generate a QR code with a specific text and size
func (t *QrService) Generate(request *GenerateRequest) (*GenerateResponse, error) {
rsp := &GenerateResponse{}
return rsp, t.client.Call("qr", "Generate", request, rsp)
}
type GenerateRequest struct {
// the size (height and width) in pixels of the generated QR code. Defaults to 256
Size int64 `json:"size,string"`
// the text to encode as a QR code (URL, phone number, email, etc)
Text string `json:"text"`
}
type GenerateResponse struct {
// link to the QR code image in PNG format
Qr string `json:"qr"`
}

View File

@@ -1,218 +0,0 @@
package quran
import (
"github.com/micro/micro-go/client"
)
func NewQuranService(token string) *QuranService {
return &QuranService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type QuranService struct {
client *client.Client
}
// List the Chapters (surahs) of the Quran
func (t *QuranService) Chapters(request *ChaptersRequest) (*ChaptersResponse, error) {
rsp := &ChaptersResponse{}
return rsp, t.client.Call("quran", "Chapters", request, rsp)
}
// Search the Quran for any form of query or questions
func (t *QuranService) Search(request *SearchRequest) (*SearchResponse, error) {
rsp := &SearchResponse{}
return rsp, t.client.Call("quran", "Search", request, rsp)
}
// Get a summary for a given chapter (surah)
func (t *QuranService) Summary(request *SummaryRequest) (*SummaryResponse, error) {
rsp := &SummaryResponse{}
return rsp, t.client.Call("quran", "Summary", request, rsp)
}
// Lookup the verses (ayahs) for a chapter including
// translation, interpretation and breakdown by individual
// words.
func (t *QuranService) Verses(request *VersesRequest) (*VersesResponse, error) {
rsp := &VersesResponse{}
return rsp, t.client.Call("quran", "Verses", request, rsp)
}
type Chapter struct {
// The arabic name of the chapter
ArabicName string `json:"arabicName"`
// The complex name of the chapter
ComplexName string `json:"complexName"`
// The id of the chapter as a number e.g 1
Id int32 `json:"id"`
// The simple name of the chapter
Name string `json:"name"`
// The pages from and to e.g 1, 1
Pages []int32 `json:"pages"`
// Should the chapter start with bismillah
PrefixBismillah bool `json:"prefixBismillah"`
// The order in which it was revealed
RevelationOrder int32 `json:"revelationOrder"`
// The place of revelation
RevelationPlace string `json:"revelationPlace"`
// The translated name
TranslatedName string `json:"translatedName"`
// The number of verses in the chapter
Verses int32 `json:"verses"`
}
type ChaptersRequest struct {
// Specify the language e.g en
Language string `json:"language"`
}
type ChaptersResponse struct {
Chapters []Chapter `json:"chapters"`
}
type Interpretation struct {
// The unique id of the interpretation
Id int32 `json:"id"`
// The source of the interpretation
Source string `json:"source"`
// The translated text
Text string `json:"text"`
}
type Result struct {
// The associated arabic text
Text string `json:"text"`
// The related translations to the text
Translations []Translation `json:"translations"`
// The unique verse id across the Quran
VerseId int32 `json:"verseId"`
// The verse key e.g 1:1
VerseKey string `json:"verseKey"`
}
type SearchRequest struct {
// The language for translation
Language string `json:"language"`
// The number of results to return
Limit int32 `json:"limit"`
// The pagination number
Page int32 `json:"page"`
// The query to ask
Query string `json:"query"`
}
type SearchResponse struct {
// The current page
Page int32 `json:"page"`
// The question asked
Query string `json:"query"`
// The results for the query
Results []Result `json:"results"`
// The total pages
TotalPages int32 `json:"totalPages"`
// The total results returned
TotalResults int32 `json:"totalResults"`
}
type SummaryRequest struct {
// The chapter id e.g 1
Chapter int32 `json:"chapter"`
// Specify the language e.g en
Language string `json:"language"`
}
type SummaryResponse struct {
// The chapter id
Chapter int32 `json:"chapter"`
// The source of the summary
Source string `json:"source"`
// The short summary for the chapter
Summary string `json:"summary"`
// The full description for the chapter
Text string `json:"text"`
}
type Translation struct {
// The unique id of the translation
Id int32 `json:"id"`
// The source of the translation
Source string `json:"source"`
// The translated text
Text string `json:"text"`
}
type Verse struct {
// The unique id of the verse in the whole book
Id int32 `json:"id"`
// The interpretations of the verse
Interpretations []Interpretation `json:"interpretations"`
// The key of this verse (chapter:verse) e.g 1:1
Key string `json:"key"`
// The verse number in this chapter
Number int32 `json:"number"`
// The page of the Quran this verse is on
Page int32 `json:"page"`
// The arabic text for this verse
Text string `json:"text"`
// The basic translation of the verse
TranslatedText string `json:"translatedText"`
// The alternative translations for the verse
Translations []Translation `json:"translations"`
// The phonetic transliteration from arabic
Transliteration string `json:"transliteration"`
// The individual words within the verse (Ayah)
Words []Word `json:"words"`
}
type VersesRequest struct {
// The chapter id to retrieve
Chapter int32 `json:"chapter"`
// Return the interpretation (tafsir)
Interpret bool `json:"interpret"`
// The language of translation
Language string `json:"language"`
// The verses per page
Limit int32 `json:"limit"`
// The page number to request
Page int32 `json:"page"`
// Return alternate translations
Translate bool `json:"translate"`
// Return the individual words with the verses
Words bool `json:"words"`
}
type VersesResponse struct {
// The chapter requested
Chapter int32 `json:"chapter"`
// The page requested
Page int32 `json:"page"`
// The total pages
TotalPages int32 `json:"totalPages"`
// The verses on the page
Verses []Verse `json:"verses"`
}
type Word struct {
// The character type e.g word, end
CharType string `json:"charType"`
// The QCF v2 font code
Code string `json:"code"`
// The id of the word within the verse
Id int32 `json:"id"`
// The line number
Line int32 `json:"line"`
// The page number
Page int32 `json:"page"`
// The position of the word
Position int32 `json:"position"`
// The arabic text for this word
Text string `json:"text"`
// The translated text
Translation string `json:"translation"`
// The transliteration text
Transliteration string `json:"transliteration"`
}

View File

@@ -1,129 +0,0 @@
package routing
import (
"github.com/micro/micro-go/client"
)
func NewRoutingService(token string) *RoutingService {
return &RoutingService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type RoutingService struct {
client *client.Client
}
// Turn by turn directions from a start point to an end point including maneuvers and bearings
func (t *RoutingService) Directions(request *DirectionsRequest) (*DirectionsResponse, error) {
rsp := &DirectionsResponse{}
return rsp, t.client.Call("routing", "Directions", request, rsp)
}
// Get the eta for a route from origin to destination. The eta is an estimated time based on car routes
func (t *RoutingService) Eta(request *EtaRequest) (*EtaResponse, error) {
rsp := &EtaResponse{}
return rsp, t.client.Call("routing", "Eta", request, rsp)
}
// Retrieve a route as a simple list of gps points along with total distance and estimated duration
func (t *RoutingService) Route(request *RouteRequest) (*RouteResponse, error) {
rsp := &RouteResponse{}
return rsp, t.client.Call("routing", "Route", request, rsp)
}
type Direction struct {
// distance to travel in meters
Distance float64 `json:"distance"`
// duration to travel in seconds
Duration float64 `json:"duration"`
// human readable instruction
Instruction string `json:"instruction"`
// intersections on route
Intersections []Intersection `json:"intersections"`
// maneuver to take
Maneuver *Maneuver `json:"maneuver"`
// street name or location
Name string `json:"name"`
// alternative reference
Reference string `json:"reference"`
}
type DirectionsRequest struct {
// The destination of the journey
Destination *Point `json:"destination"`
// The staring point for the journey
Origin *Point `json:"origin"`
}
type DirectionsResponse struct {
// Turn by turn directions
Directions []Direction `json:"directions"`
// Estimated distance of the route in meters
Distance float64 `json:"distance"`
// Estimated duration of the route in seconds
Duration float64 `json:"duration"`
// The waypoints on the route
Waypoints []Waypoint `json:"waypoints"`
}
type EtaRequest struct {
// The end point for the eta calculation
Destination *Point `json:"destination"`
// The starting point for the eta calculation
Origin *Point `json:"origin"`
// speed in kilometers
Speed float64 `json:"speed"`
// type of transport. Only "car" is supported currently.
Type string `json:"type"`
}
type EtaResponse struct {
// eta in seconds
Duration float64 `json:"duration"`
}
type Intersection struct {
Bearings []float64 `json:"bearings"`
Location *Point `json:"location"`
}
type Maneuver struct {
Action string `json:"action"`
BearingAfter float64 `json:"bearingAfter"`
BearingBefore float64 `json:"bearingBefore"`
Direction string `json:"direction"`
Location *Point `json:"location"`
}
type Point struct {
// Lat e.g 52.523219
Latitude float64 `json:"latitude"`
// Long e.g 13.428555
Longitude float64 `json:"longitude"`
}
type RouteRequest struct {
// Point of destination for the trip
Destination *Point `json:"destination"`
// Point of origin for the trip
Origin *Point `json:"origin"`
}
type RouteResponse struct {
// estimated distance in meters
Distance float64 `json:"distance"`
// estimated duration in seconds
Duration float64 `json:"duration"`
// waypoints on the route
Waypoints []Waypoint `json:"waypoints"`
}
type Waypoint struct {
// gps point coordinates
Location *Point `json:"location"`
// street name or related reference
Name string `json:"name"`
}

View File

@@ -1,114 +0,0 @@
package rss
import (
"github.com/micro/micro-go/client"
)
func NewRssService(token string) *RssService {
return &RssService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type RssService struct {
client *client.Client
}
// Add a new RSS feed with a name, url, and category
func (t *RssService) Add(request *AddRequest) (*AddResponse, error) {
rsp := &AddResponse{}
return rsp, t.client.Call("rss", "Add", request, rsp)
}
// Get an RSS feed by name. If no name is given, all feeds are returned. Default limit is 25 entries.
func (t *RssService) Feed(request *FeedRequest) (*FeedResponse, error) {
rsp := &FeedResponse{}
return rsp, t.client.Call("rss", "Feed", request, rsp)
}
// List the saved RSS fields
func (t *RssService) List(request *ListRequest) (*ListResponse, error) {
rsp := &ListResponse{}
return rsp, t.client.Call("rss", "List", request, rsp)
}
// Remove an RSS feed by name
func (t *RssService) Remove(request *RemoveRequest) (*RemoveResponse, error) {
rsp := &RemoveResponse{}
return rsp, t.client.Call("rss", "Remove", request, rsp)
}
type AddRequest struct {
// category to add e.g news
Category string `json:"category"`
// rss feed name
// eg. a16z
Name string `json:"name"`
// rss feed url
// eg. http://a16z.com/feed/
Url string `json:"url"`
}
type AddResponse struct {
}
type Entry struct {
// article content
Content string `json:"content"`
// data of the entry
Date string `json:"date"`
// the rss feed where it came from
Feed string `json:"feed"`
// unique id of the entry
Id string `json:"id"`
// rss feed url of the entry
Link string `json:"link"`
// article summary
Summary string `json:"summary"`
// title of the entry
Title string `json:"title"`
}
type Feed struct {
// category of the feed e.g news
Category string `json:"category"`
// unique id
Id string `json:"id"`
// rss feed name
// eg. a16z
Name string `json:"name"`
// rss feed url
// eg. http://a16z.com/feed/
Url string `json:"url"`
}
type FeedRequest struct {
// limit entries returned
Limit int64 `json:"limit,string"`
// rss feed name
Name string `json:"name"`
// offset entries
Offset int64 `json:"offset,string"`
}
type FeedResponse struct {
Entries []Entry `json:"entries"`
}
type ListRequest struct {
}
type ListResponse struct {
Feeds []Feed `json:"feeds"`
}
type RemoveRequest struct {
// rss feed name
// eg. a16z
Name string `json:"name"`
}
type RemoveResponse struct {
}

View File

@@ -1,35 +0,0 @@
package sentiment
import (
"github.com/micro/micro-go/client"
)
func NewSentimentService(token string) *SentimentService {
return &SentimentService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type SentimentService struct {
client *client.Client
}
// Analyze and score a piece of text
func (t *SentimentService) Analyze(request *AnalyzeRequest) (*AnalyzeResponse, error) {
rsp := &AnalyzeResponse{}
return rsp, t.client.Call("sentiment", "Analyze", request, rsp)
}
type AnalyzeRequest struct {
// The language. Defaults to english.
Lang string `json:"lang"`
// The text to analyze
Text string `json:"text"`
}
type AnalyzeResponse struct {
// The score of the text {positive is 1, negative is 0}
Score float64 `json:"score"`
}

View File

@@ -1,39 +0,0 @@
package sms
import (
"github.com/micro/micro-go/client"
)
func NewSmsService(token string) *SmsService {
return &SmsService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type SmsService struct {
client *client.Client
}
// Send an SMS.
func (t *SmsService) Send(request *SendRequest) (*SendResponse, error) {
rsp := &SendResponse{}
return rsp, t.client.Call("sms", "Send", request, rsp)
}
type SendRequest struct {
// who is the message from? The message will be suffixed with "Sent from <from>"
From string `json:"from"`
// the main body of the message to send
Message string `json:"message"`
// the destination phone number including the international dialling code (e.g. +44)
To string `json:"to"`
}
type SendResponse struct {
// any additional info
Info string `json:"info"`
// will return "ok" if successful
Status string `json:"status"`
}

View File

@@ -1,47 +0,0 @@
package spam
import (
"github.com/micro/micro-go/client"
)
func NewSpamService(token string) *SpamService {
return &SpamService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type SpamService struct {
client *client.Client
}
// Check whether an email is likely to be spam based on its attributes
func (t *SpamService) Classify(request *ClassifyRequest) (*ClassifyResponse, error) {
rsp := &ClassifyResponse{}
return rsp, t.client.Call("spam", "Classify", request, rsp)
}
type ClassifyRequest struct {
// The raw body of the email including headers etc per RFC 822. Alternatively, use the other parameters to correctly format the message
EmailBody string `json:"emailBody"`
// The email address it has been sent from
From string `json:"from"`
// the HTML version of the email body
HtmlBody string `json:"htmlBody"`
// The subject of the email
Subject string `json:"subject"`
// the plain text version of the email body
TextBody string `json:"textBody"`
// The email address it is being sent to
To string `json:"to"`
}
type ClassifyResponse struct {
// The rules that have contributed to this score
Details []string `json:"details"`
// Is it spam? Returns true if its score is > 5
IsSpam bool `json:"isSpam"`
// The score evaluated for this email. A higher number means it is more likely to be spam
Score float64 `json:"score"`
}

View File

@@ -1,132 +0,0 @@
package stock
import (
"github.com/micro/micro-go/client"
)
func NewStockService(token string) *StockService {
return &StockService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type StockService struct {
client *client.Client
}
// Get the historic open-close for a given day
func (t *StockService) History(request *HistoryRequest) (*HistoryResponse, error) {
rsp := &HistoryResponse{}
return rsp, t.client.Call("stock", "History", request, rsp)
}
// Get the historic order book and each trade by timestamp
func (t *StockService) OrderBook(request *OrderBookRequest) (*OrderBookResponse, error) {
rsp := &OrderBookResponse{}
return rsp, t.client.Call("stock", "OrderBook", request, rsp)
}
// Get the last price for a given stock ticker
func (t *StockService) Price(request *PriceRequest) (*PriceResponse, error) {
rsp := &PriceResponse{}
return rsp, t.client.Call("stock", "Price", request, rsp)
}
// Get the last quote for the stock
func (t *StockService) Quote(request *QuoteRequest) (*QuoteResponse, error) {
rsp := &QuoteResponse{}
return rsp, t.client.Call("stock", "Quote", request, rsp)
}
type HistoryRequest struct {
// date to retrieve as YYYY-MM-DD
Date string `json:"date"`
// the stock symbol e.g AAPL
Stock string `json:"stock"`
}
type HistoryResponse struct {
// the close price
Close float64 `json:"close"`
// the date
Date string `json:"date"`
// the peak price
High float64 `json:"high"`
// the low price
Low float64 `json:"low"`
// the open price
Open float64 `json:"open"`
// the stock symbol
Symbol string `json:"symbol"`
// the volume
Volume int32 `json:"volume"`
}
type Order struct {
// the asking price
AskPrice float64 `json:"askPrice"`
// the ask size
AskSize int32 `json:"askSize"`
// the bidding price
BidPrice float64 `json:"bidPrice"`
// the bid size
BidSize int32 `json:"bidSize"`
// the UTC timestamp of the quote
Timestamp string `json:"timestamp"`
}
type OrderBookRequest struct {
// the date in format YYYY-MM-dd
Date string `json:"date"`
// optional RFC3339Nano end time e.g 2006-01-02T15:04:05.999999999Z07:00
End string `json:"end"`
// limit number of prices
Limit int32 `json:"limit"`
// optional RFC3339Nano start time e.g 2006-01-02T15:04:05.999999999Z07:00
Start string `json:"start"`
// stock to retrieve e.g AAPL
Stock string `json:"stock"`
}
type OrderBookResponse struct {
// date of the request
Date string `json:"date"`
// list of orders
Orders []Order `json:"orders"`
// the stock symbol
Symbol string `json:"symbol"`
}
type PriceRequest struct {
// stock symbol e.g AAPL
Symbol string `json:"symbol"`
}
type PriceResponse struct {
// the last price
Price float64 `json:"price"`
// the stock symbol e.g AAPL
Symbol string `json:"symbol"`
}
type QuoteRequest struct {
// the stock symbol e.g AAPL
Symbol string `json:"symbol"`
}
type QuoteResponse struct {
// the asking price
AskPrice float64 `json:"askPrice"`
// the ask size
AskSize int32 `json:"askSize"`
// the bidding price
BidPrice float64 `json:"bidPrice"`
// the bid size
BidSize int32 `json:"bidSize"`
// the stock symbol
Symbol string `json:"symbol"`
// the UTC timestamp of the quote
Timestamp string `json:"timestamp"`
}

View File

@@ -1,105 +0,0 @@
package stream
import (
"github.com/micro/micro-go/client"
)
func NewStreamService(token string) *StreamService {
return &StreamService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type StreamService struct {
client *client.Client
}
// Create a channel with a given name and description. Channels are created automatically but
// this allows you to specify a description that's persisted for the lifetime of the channel.
func (t *StreamService) CreateChannel(request *CreateChannelRequest) (*CreateChannelResponse, error) {
rsp := &CreateChannelResponse{}
return rsp, t.client.Call("stream", "CreateChannel", request, rsp)
}
// List all the active channels
func (t *StreamService) ListChannels(request *ListChannelsRequest) (*ListChannelsResponse, error) {
rsp := &ListChannelsResponse{}
return rsp, t.client.Call("stream", "ListChannels", request, rsp)
}
// List messages for a given channel
func (t *StreamService) ListMessages(request *ListMessagesRequest) (*ListMessagesResponse, error) {
rsp := &ListMessagesResponse{}
return rsp, t.client.Call("stream", "ListMessages", request, rsp)
}
// Send a message to the stream.
func (t *StreamService) SendMessage(request *SendMessageRequest) (*SendMessageResponse, error) {
rsp := &SendMessageResponse{}
return rsp, t.client.Call("stream", "SendMessage", request, rsp)
}
type Channel struct {
// description for the channel
Description string `json:"description"`
// last activity time
LastActive string `json:"lastActive"`
// name of the channel
Name string `json:"name"`
}
type CreateChannelRequest struct {
// description for the channel
Description string `json:"description"`
// name of the channel
Name string `json:"name"`
}
type CreateChannelResponse struct {
}
type ListChannelsRequest struct {
}
type ListChannelsResponse struct {
Channels []Channel `json:"channels"`
}
type ListMessagesRequest struct {
// The channel to subscribe to
Channel string `json:"channel"`
// number of message to return
Limit int32 `json:"limit"`
}
type ListMessagesResponse struct {
// The channel subscribed to
Channel string `json:"channel"`
// Messages are chronological order
Messages []Message `json:"messages"`
}
type Message struct {
// the channel name
Channel string `json:"channel"`
// id of the message
Id string `json:"id"`
// the associated metadata
Metadata map[string]string `json:"metadata"`
// text of the message
Text string `json:"text"`
// time of message creation
Timestamp string `json:"timestamp"`
}
type SendMessageRequest struct {
// The channel to send to
Channel string `json:"channel"`
// The message text to send
Text string `json:"text"`
}
type SendMessageResponse struct {
}

View File

@@ -1,183 +0,0 @@
package sunnah
import (
"github.com/micro/micro-go/client"
)
func NewSunnahService(token string) *SunnahService {
return &SunnahService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type SunnahService struct {
client *client.Client
}
// Get a list of books from within a collection. A book can contain many chapters
// each with its own hadiths.
func (t *SunnahService) Books(request *BooksRequest) (*BooksResponse, error) {
rsp := &BooksResponse{}
return rsp, t.client.Call("sunnah", "Books", request, rsp)
}
// Get all the chapters of a given book within a collection.
func (t *SunnahService) Chapters(request *ChaptersRequest) (*ChaptersResponse, error) {
rsp := &ChaptersResponse{}
return rsp, t.client.Call("sunnah", "Chapters", request, rsp)
}
// Get a list of available collections. A collection is
// a compilation of hadiths collected and written by an author.
func (t *SunnahService) Collections(request *CollectionsRequest) (*CollectionsResponse, error) {
rsp := &CollectionsResponse{}
return rsp, t.client.Call("sunnah", "Collections", request, rsp)
}
// Hadiths returns a list of hadiths and their corresponding text for a
// given book within a collection.
func (t *SunnahService) Hadiths(request *HadithsRequest) (*HadithsResponse, error) {
rsp := &HadithsResponse{}
return rsp, t.client.Call("sunnah", "Hadiths", request, rsp)
}
type Book struct {
// arabic name of the book
ArabicName string `json:"arabicName"`
// number of hadiths in the book
Hadiths int32 `json:"hadiths"`
// number of the book e.g 1
Id int32 `json:"id"`
// name of the book
Name string `json:"name"`
}
type BooksRequest struct {
// Name of the collection
Collection string `json:"collection"`
// Limit the number of books returned
Limit int32 `json:"limit"`
// The page in the pagination
Page int32 `json:"page"`
}
type BooksResponse struct {
// A list of books
Books []Book `json:"books"`
// Name of the collection
Collection string `json:"collection"`
// The limit specified
Limit int32 `json:"limit"`
// The page requested
Page int32 `json:"page"`
// The total overall books
Total int32 `json:"total"`
}
type Chapter struct {
// arabic title
ArabicTitle string `json:"arabicTitle"`
// the book number
Book int32 `json:"book"`
// the chapter id e.g 1
Id int32 `json:"id"`
// the chapter key e.g 1.00
Key string `json:"key"`
// title of the chapter
Title string `json:"title"`
}
type ChaptersRequest struct {
// number of the book
Book int32 `json:"book"`
// name of the collection
Collection string `json:"collection"`
// Limit the number of chapters returned
Limit int32 `json:"limit"`
// The page in the pagination
Page int32 `json:"page"`
}
type ChaptersResponse struct {
// number of the book
Book int32 `json:"book"`
// The chapters of the book
Chapters []Chapter `json:"chapters"`
// name of the collection
Collection string `json:"collection"`
// Limit the number of chapters returned
Limit int32 `json:"limit"`
// The page in the pagination
Page int32 `json:"page"`
// Total chapters in the book
Total int32 `json:"total"`
}
type Collection struct {
// Arabic title if available
ArabicTitle string `json:"arabicTitle"`
// Total hadiths in the collection
Hadiths int32 `json:"hadiths"`
// Name of the collection e.g bukhari
Name string `json:"name"`
// An introduction explaining the collection
Summary string `json:"summary"`
// Title of the collection e.g Sahih al-Bukhari
Title string `json:"title"`
}
type CollectionsRequest struct {
// Number of collections to limit to
Limit int32 `json:"limit"`
// The page in the pagination
Page int32 `json:"page"`
}
type CollectionsResponse struct {
Collections []Collection `json:"collections"`
}
type Hadith struct {
// the arabic chapter title
ArabicChapterTitle string `json:"arabicChapterTitle"`
// the arabic text
ArabicText string `json:"arabicText"`
// the chapter id
Chapter int32 `json:"chapter"`
// the chapter key
ChapterKey string `json:"chapterKey"`
// the chapter title
ChapterTitle string `json:"chapterTitle"`
// hadith id
Id int32 `json:"id"`
// hadith text
Text string `json:"text"`
}
type HadithsRequest struct {
// number of the book
Book int32 `json:"book"`
// name of the collection
Collection string `json:"collection"`
// Limit the number of hadiths
Limit int32 `json:"limit"`
// The page in the pagination
Page int32 `json:"page"`
}
type HadithsResponse struct {
// number of the book
Book int32 `json:"book"`
// name of the collection
Collection string `json:"collection"`
// The hadiths of the book
Hadiths []Hadith `json:"hadiths"`
// Limit the number of hadiths returned
Limit int32 `json:"limit"`
// The page in the pagination
Page int32 `json:"page"`
// Total hadiths in the book
Total int32 `json:"total"`
}

View File

@@ -1,35 +0,0 @@
package thumbnail
import (
"github.com/micro/micro-go/client"
)
func NewThumbnailService(token string) *ThumbnailService {
return &ThumbnailService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type ThumbnailService struct {
client *client.Client
}
// Create a thumbnail screenshot by passing in a url, height and width
func (t *ThumbnailService) Screenshot(request *ScreenshotRequest) (*ScreenshotResponse, error) {
rsp := &ScreenshotResponse{}
return rsp, t.client.Call("thumbnail", "Screenshot", request, rsp)
}
type ScreenshotRequest struct {
// height of the browser window, optional
Height int32 `json:"height"`
Url string `json:"url"`
// width of the browser window. optional
Width int32 `json:"width"`
}
type ScreenshotResponse struct {
ImageUrl string `json:"imageUrl"`
}

View File

@@ -1,73 +0,0 @@
package time
import (
"github.com/micro/micro-go/client"
)
func NewTimeService(token string) *TimeService {
return &TimeService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type TimeService struct {
client *client.Client
}
// Get the current time
func (t *TimeService) Now(request *NowRequest) (*NowResponse, error) {
rsp := &NowResponse{}
return rsp, t.client.Call("time", "Now", request, rsp)
}
// Get the timezone info for a specific location
func (t *TimeService) Zone(request *ZoneRequest) (*ZoneResponse, error) {
rsp := &ZoneResponse{}
return rsp, t.client.Call("time", "Zone", request, rsp)
}
type NowRequest struct {
// optional location, otherwise returns UTC
Location string `json:"location"`
}
type NowResponse struct {
// the current time as HH:MM:SS
Localtime string `json:"localtime"`
// the location as Europe/London
Location string `json:"location"`
// timestamp as 2006-01-02T15:04:05.999999999Z07:00
Timestamp string `json:"timestamp"`
// the timezone as BST
Timezone string `json:"timezone"`
// the unix timestamp
Unix int64 `json:"unix,string"`
}
type ZoneRequest struct {
// location to lookup e.g postcode, city, ip address
Location string `json:"location"`
}
type ZoneResponse struct {
// the abbreviated code e.g BST
Abbreviation string `json:"abbreviation"`
// country of the timezone
Country string `json:"country"`
// is daylight savings
Dst bool `json:"dst"`
// e.g 51.42
Latitude float64 `json:"latitude"`
// the local time
Localtime string `json:"localtime"`
// location requested
Location string `json:"location"`
// e.g -0.37
Longitude float64 `json:"longitude"`
// region of timezone
Region string `json:"region"`
// the timezone e.g Europe/London
Timezone string `json:"timezone"`
}

View File

@@ -1,132 +0,0 @@
package twitter
import (
"github.com/micro/micro-go/client"
)
func NewTwitterService(token string) *TwitterService {
return &TwitterService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type TwitterService struct {
client *client.Client
}
// Search for tweets with a simple query
func (t *TwitterService) Search(request *SearchRequest) (*SearchResponse, error) {
rsp := &SearchResponse{}
return rsp, t.client.Call("twitter", "Search", request, rsp)
}
// Get the timeline for a given user
func (t *TwitterService) Timeline(request *TimelineRequest) (*TimelineResponse, error) {
rsp := &TimelineResponse{}
return rsp, t.client.Call("twitter", "Timeline", request, rsp)
}
// Get the current global trending topics
func (t *TwitterService) Trends(request *TrendsRequest) (*TrendsResponse, error) {
rsp := &TrendsResponse{}
return rsp, t.client.Call("twitter", "Trends", request, rsp)
}
// Get a user's twitter profile
func (t *TwitterService) User(request *UserRequest) (*UserResponse, error) {
rsp := &UserResponse{}
return rsp, t.client.Call("twitter", "User", request, rsp)
}
type Profile struct {
// the account creation date
CreatedAt string `json:"createdAt"`
// the user description
Description string `json:"description"`
// the follower count
Followers int64 `json:"followers,string"`
// the user id
Id int64 `json:"id,string"`
// The user's profile picture
ImageUrl string `json:"imageUrl"`
// the user's location
Location string `json:"location"`
// display name of the user
Name string `json:"name"`
// if the account is private
Private bool `json:"private"`
// the username
Username string `json:"username"`
// if the account is verified
Verified bool `json:"verified"`
}
type SearchRequest struct {
// number of tweets to return. default: 20
Limit int32 `json:"limit"`
// the query to search for
Query string `json:"query"`
}
type SearchResponse struct {
// the related tweets for the search
Tweets []Tweet `json:"tweets"`
}
type TimelineRequest struct {
// number of tweets to return. default: 20
Limit int32 `json:"limit"`
// the username to request the timeline for
Username string `json:"username"`
}
type TimelineResponse struct {
// The recent tweets for the user
Tweets []Tweet `json:"tweets"`
}
type Trend struct {
// name of the trend
Name string `json:"name"`
// the volume of tweets in last 24 hours
TweetVolume int64 `json:"tweetVolume,string"`
// the twitter url
Url string `json:"url"`
}
type TrendsRequest struct {
}
type TrendsResponse struct {
// a list of trending topics
Trends []Trend `json:"trends"`
}
type Tweet struct {
// time of tweet
CreatedAt string `json:"createdAt"`
// number of times favourited
FavouritedCount int64 `json:"favouritedCount,string"`
// id of the tweet
Id int64 `json:"id,string"`
// number of times retweeted
RetweetedCount int64 `json:"retweetedCount,string"`
// text of the tweet
Text string `json:"text"`
// username of the person who tweeted
Username string `json:"username"`
}
type UserRequest struct {
// the username to lookup
Username string `json:"username"`
}
type UserResponse struct {
// The requested user profile
Profile *Profile `json:"profile"`
// the current user status
Status *Tweet `json:"status"`
}

View File

@@ -1,73 +0,0 @@
package url
import (
"github.com/micro/micro-go/client"
)
func NewUrlService(token string) *UrlService {
return &UrlService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type UrlService struct {
client *client.Client
}
// List information on all the shortened URLs that you have created
func (t *UrlService) List(request *ListRequest) (*ListResponse, error) {
rsp := &ListResponse{}
return rsp, t.client.Call("url", "List", request, rsp)
}
// Proxy returns the destination URL of a short URL.
func (t *UrlService) Proxy(request *ProxyRequest) (*ProxyResponse, error) {
rsp := &ProxyResponse{}
return rsp, t.client.Call("url", "Proxy", request, rsp)
}
// Shortens a destination URL and returns a full short URL.
func (t *UrlService) Shorten(request *ShortenRequest) (*ShortenResponse, error) {
rsp := &ShortenResponse{}
return rsp, t.client.Call("url", "Shorten", request, rsp)
}
type ListRequest struct {
// filter by short URL, optional
ShortUrl string `json:"shortUrl"`
}
type ListResponse struct {
UrlPairs *URLPair `json:"urlPairs"`
}
type ProxyRequest struct {
// short url ID, without the domain, eg. if your short URL is
// `m3o.one/u/someshorturlid` then pass in `someshorturlid`
ShortUrl string `json:"shortUrl"`
}
type ProxyResponse struct {
DestinationUrl string `json:"destinationUrl"`
}
type ShortenRequest struct {
DestinationUrl string `json:"destinationUrl"`
}
type ShortenResponse struct {
ShortUrl string `json:"shortUrl"`
}
type URLPair struct {
Created int64 `json:"created,string"`
DestinationUrl string `json:"destinationUrl"`
// HitCount keeps track many times the short URL has been resolved.
// Hitcount only gets saved to disk (database) after every 10th hit, so
// its not intended to be 100% accurate, more like an almost correct estimate.
HitCount int64 `json:"hitCount,string"`
Owner string `json:"owner"`
ShortUrl string `json:"shortUrl"`
}

View File

@@ -1,281 +0,0 @@
package user
import (
"github.com/micro/micro-go/client"
)
func NewUserService(token string) *UserService {
return &UserService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type UserService struct {
client *client.Client
}
// Create a new user account. The email address and username for the account must be unique.
func (t *UserService) Create(request *CreateRequest) (*CreateResponse, error) {
rsp := &CreateResponse{}
return rsp, t.client.Call("user", "Create", request, rsp)
}
// Delete an account by id
func (t *UserService) Delete(request *DeleteRequest) (*DeleteResponse, error) {
rsp := &DeleteResponse{}
return rsp, t.client.Call("user", "Delete", request, rsp)
}
// Login using username or email. The response will return a new session for successful login,
// 401 in the case of login failure and 500 for any other error
func (t *UserService) Login(request *LoginRequest) (*LoginResponse, error) {
rsp := &LoginResponse{}
return rsp, t.client.Call("user", "Login", request, rsp)
}
// Logout a user account
func (t *UserService) Logout(request *LogoutRequest) (*LogoutResponse, error) {
rsp := &LogoutResponse{}
return rsp, t.client.Call("user", "Logout", request, rsp)
}
// Read an account by id, username or email. Only one need to be specified.
func (t *UserService) Read(request *ReadRequest) (*ReadResponse, error) {
rsp := &ReadResponse{}
return rsp, t.client.Call("user", "Read", request, rsp)
}
// Read a session by the session id. In the event it has expired or is not found and error is returned.
func (t *UserService) ReadSession(request *ReadSessionRequest) (*ReadSessionResponse, error) {
rsp := &ReadSessionResponse{}
return rsp, t.client.Call("user", "ReadSession", request, rsp)
}
// Reset password with the code sent by the "SendPasswordResetEmail" endoint.
func (t *UserService) ResetPassword(request *ResetPasswordRequest) (*ResetPasswordResponse, error) {
rsp := &ResetPasswordResponse{}
return rsp, t.client.Call("user", "ResetPassword", request, rsp)
}
// Send an email with a verification code to reset password.
// Call "ResetPassword" endpoint once user provides the code.
func (t *UserService) SendPasswordResetEmail(request *SendPasswordResetEmailRequest) (*SendPasswordResetEmailResponse, error) {
rsp := &SendPasswordResetEmailResponse{}
return rsp, t.client.Call("user", "SendPasswordResetEmail", request, rsp)
}
// Send a verification email
// to the user being signed up. Email from will be from 'noreply@email.m3ocontent.com',
// but you can provide the title and contents.
// The verification link will be injected in to the email as a template variable, $micro_verification_link.
// Example: 'Hi there, welcome onboard! Use the link below to verify your email: $micro_verification_link'
// The variable will be replaced with an actual url that will look similar to this:
// 'https://user.m3o.com/user/verify?token=a-verification-token&redirectUrl=your-redir-url'
func (t *UserService) SendVerificationEmail(request *SendVerificationEmailRequest) (*SendVerificationEmailResponse, error) {
rsp := &SendVerificationEmailResponse{}
return rsp, t.client.Call("user", "SendVerificationEmail", request, rsp)
}
// Update the account password
func (t *UserService) UpdatePassword(request *UpdatePasswordRequest) (*UpdatePasswordResponse, error) {
rsp := &UpdatePasswordResponse{}
return rsp, t.client.Call("user", "UpdatePassword", request, rsp)
}
// Update the account username or email
func (t *UserService) Update(request *UpdateRequest) (*UpdateResponse, error) {
rsp := &UpdateResponse{}
return rsp, t.client.Call("user", "Update", request, rsp)
}
// Verify the email address of an account from a token sent in an email to the user.
func (t *UserService) VerifyEmail(request *VerifyEmailRequest) (*VerifyEmailResponse, error) {
rsp := &VerifyEmailResponse{}
return rsp, t.client.Call("user", "VerifyEmail", request, rsp)
}
type Account struct {
// unix timestamp
Created int64 `json:"created,string"`
// an email address
Email string `json:"email"`
// unique account id
Id string `json:"id"`
// Store any custom data you want about your users in this fields.
Profile map[string]string `json:"profile"`
// unix timestamp
Updated int64 `json:"updated,string"`
// alphanumeric username
Username string `json:"username"`
// date of verification
VerificationDate int64 `json:"verificationDate,string"`
// if the account is verified
Verified bool `json:"verified"`
}
type CreateRequest struct {
// the email address
Email string `json:"email"`
// optional account id
Id string `json:"id"`
// the user password
Password string `json:"password"`
// optional user profile as map<string,string>
Profile map[string]string `json:"profile"`
// the username
Username string `json:"username"`
}
type CreateResponse struct {
Account *Account `json:"account"`
}
type DeleteRequest struct {
// the account id
Id string `json:"id"`
}
type DeleteResponse struct {
}
type LoginRequest struct {
// The email address of the user
Email string `json:"email"`
// The password of the user
Password string `json:"password"`
// The username of the user
Username string `json:"username"`
}
type LoginResponse struct {
// The session of the logged in user
Session *Session `json:"session"`
}
type LogoutRequest struct {
// the session id for the user to logout
SessionId string `json:"sessionId"`
}
type LogoutResponse struct {
}
type ReadRequest struct {
// the account email
Email string `json:"email"`
// the account id
Id string `json:"id"`
// the account username
Username string `json:"username"`
}
type ReadResponse struct {
Account *Account `json:"account"`
}
type ReadSessionRequest struct {
// The unique session id
SessionId string `json:"sessionId"`
}
type ReadSessionResponse struct {
// the session for the user
Session *Session `json:"session"`
}
type ResetPasswordRequest struct {
// The code from the verification email
Code string `json:"code"`
// confirm new password
ConfirmPassword string `json:"confirmPassword"`
// the email to reset the password for
Email string `json:"email"`
// the new password
NewPassword string `json:"newPassword"`
}
type ResetPasswordResponse struct {
}
type SendPasswordResetEmailRequest struct {
// email address to send reset for
Email string `json:"email"`
// Display name of the sender for the email. Note: the email address will still be 'noreply@email.m3ocontent.com'
FromName string `json:"fromName"`
// subject of the email
Subject string `json:"subject"`
// Text content of the email. Don't forget to include the string '$code' which will be replaced by the real verification link
// HTML emails are not available currently.
TextContent string `json:"textContent"`
}
type SendPasswordResetEmailResponse struct {
}
type SendVerificationEmailRequest struct {
// email address to send the verification code
Email string `json:"email"`
FailureRedirectUrl string `json:"failureRedirectUrl"`
// Display name of the sender for the email. Note: the email address will still be 'noreply@email.m3ocontent.com'
FromName string `json:"fromName"`
RedirectUrl string `json:"redirectUrl"`
// subject of the email
Subject string `json:"subject"`
// Text content of the email. Don't forget to include the string '$micro_verification_link' which will be replaced by the real verification link
// HTML emails are not available currently.
TextContent string `json:"textContent"`
}
type SendVerificationEmailResponse struct {
}
type Session struct {
// unix timestamp
Created int64 `json:"created,string"`
// unix timestamp
Expires int64 `json:"expires,string"`
// the session id
Id string `json:"id"`
// the associated user id
UserId string `json:"userId"`
}
type UpdatePasswordRequest struct {
// confirm new password
ConfirmPassword string `json:"confirmPassword"`
// the new password
NewPassword string `json:"newPassword"`
// the old password
OldPassword string `json:"oldPassword"`
// the account id
UserId string `json:"userId"`
}
type UpdatePasswordResponse struct {
}
type UpdateRequest struct {
// the new email address
Email string `json:"email"`
// the account id
Id string `json:"id"`
// the user profile as map<string,string>
Profile map[string]string `json:"profile"`
// the new username
Username string `json:"username"`
}
type UpdateResponse struct {
}
type VerifyEmailRequest struct {
// the email address to verify
Email string `json:"email"`
// The token from the verification email
Token string `json:"token"`
}
type VerifyEmailResponse struct {
}

View File

@@ -1,61 +0,0 @@
package vehicle
import (
"github.com/micro/micro-go/client"
)
func NewVehicleService(token string) *VehicleService {
return &VehicleService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type VehicleService struct {
client *client.Client
}
// Lookup a UK vehicle by it's registration number
func (t *VehicleService) Lookup(request *LookupRequest) (*LookupResponse, error) {
rsp := &LookupResponse{}
return rsp, t.client.Call("vehicle", "Lookup", request, rsp)
}
type LookupRequest struct {
// the vehicle registration number
Registration string `json:"registration"`
}
type LookupResponse struct {
// co2 emmissions
Co2emissions float64 `json:"co2emissions"`
// colour of vehicle
Colour string `json:"colour"`
// engine capacity
EngineCapacity int32 `json:"engineCapacity"`
// fuel type e.g petrol, diesel
FuelType string `json:"fuelType"`
// date of last v5 issue
LastV5issued string `json:"lastV5issued"`
// make of vehicle
Make string `json:"make"`
// month of first registration
MonthOfFirstRegistration string `json:"monthOfFirstRegistration"`
// mot expiry
MotExpiry string `json:"motExpiry"`
// mot status
MotStatus string `json:"motStatus"`
// registration number
Registration string `json:"registration"`
// tax due data
TaxDueDate string `json:"taxDueDate"`
// tax status
TaxStatus string `json:"taxStatus"`
// type approvale
TypeApproval string `json:"typeApproval"`
// wheel plan
Wheelplan string `json:"wheelplan"`
// year of manufacture
YearOfManufacture int32 `json:"yearOfManufacture"`
}

View File

@@ -1,132 +0,0 @@
package weather
import (
"github.com/micro/micro-go/client"
)
func NewWeatherService(token string) *WeatherService {
return &WeatherService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type WeatherService struct {
client *client.Client
}
// Get the weather forecast for the next 1-10 days
func (t *WeatherService) Forecast(request *ForecastRequest) (*ForecastResponse, error) {
rsp := &ForecastResponse{}
return rsp, t.client.Call("weather", "Forecast", request, rsp)
}
// Get the current weather report for a location by postcode, city, zip code, ip address
func (t *WeatherService) Now(request *NowRequest) (*NowResponse, error) {
rsp := &NowResponse{}
return rsp, t.client.Call("weather", "Now", request, rsp)
}
type Forecast struct {
// the average temp in celsius
AvgTempC float64 `json:"avgTempC"`
// the average temp in fahrenheit
AvgTempF float64 `json:"avgTempF"`
// chance of rain (percentage)
ChanceOfRain int32 `json:"chanceOfRain"`
// forecast condition
Condition string `json:"condition"`
// date of the forecast
Date string `json:"date"`
// the URL of forecast condition icon. Simply prefix with either http or https to use it
IconUrl string `json:"iconUrl"`
// max temp in celsius
MaxTempC float64 `json:"maxTempC"`
// max temp in fahrenheit
MaxTempF float64 `json:"maxTempF"`
// minimum temp in celsius
MinTempC float64 `json:"minTempC"`
// minimum temp in fahrenheit
MinTempF float64 `json:"minTempF"`
// time of sunrise
Sunrise string `json:"sunrise"`
// time of sunset
Sunset string `json:"sunset"`
// will it rain
WillItRain bool `json:"willItRain"`
}
type ForecastRequest struct {
// number of days. default 1, max 10
Days int32 `json:"days"`
// location of the forecase
Location string `json:"location"`
}
type ForecastResponse struct {
// country of the request
Country string `json:"country"`
// forecast for the next number of days
Forecast []Forecast `json:"forecast"`
// e.g 37.55
Latitude float64 `json:"latitude"`
// the local time
LocalTime string `json:"localTime"`
// location of the request
Location string `json:"location"`
// e.g -77.46
Longitude float64 `json:"longitude"`
// region related to the location
Region string `json:"region"`
// timezone of the location
Timezone string `json:"timezone"`
}
type NowRequest struct {
// location to get weather e.g postcode, city
Location string `json:"location"`
}
type NowResponse struct {
// cloud cover percentage
Cloud int32 `json:"cloud"`
// the weather condition
Condition string `json:"condition"`
// country of the request
Country string `json:"country"`
// whether its daytime
Daytime bool `json:"daytime"`
// feels like in celsius
FeelsLikeC float64 `json:"feelsLikeC"`
// feels like in fahrenheit
FeelsLikeF float64 `json:"feelsLikeF"`
// the humidity percentage
Humidity int32 `json:"humidity"`
// the URL of the related icon. Simply prefix with either http or https to use it
IconUrl string `json:"iconUrl"`
// e.g 37.55
Latitude float64 `json:"latitude"`
// the local time
LocalTime string `json:"localTime"`
// location of the request
Location string `json:"location"`
// e.g -77.46
Longitude float64 `json:"longitude"`
// region related to the location
Region string `json:"region"`
// temperature in celsius
TempC float64 `json:"tempC"`
// temperature in fahrenheit
TempF float64 `json:"tempF"`
// timezone of the location
Timezone string `json:"timezone"`
// wind degree
WindDegree int32 `json:"windDegree"`
// wind direction
WindDirection string `json:"windDirection"`
// wind in kph
WindKph float64 `json:"windKph"`
// wind in mph
WindMph float64 `json:"windMph"`
}

View File

@@ -1,55 +0,0 @@
package youtube
import (
"github.com/micro/micro-go/client"
)
func NewYoutubeService(token string) *YoutubeService {
return &YoutubeService{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type YoutubeService struct {
client *client.Client
}
// Search for videos on YouTube
func (t *YoutubeService) Search(request *SearchRequest) (*SearchResponse, error) {
rsp := &SearchResponse{}
return rsp, t.client.Call("youtube", "Search", request, rsp)
}
type SearchRequest struct {
// Query to search for
Query string `json:"query"`
}
type SearchResponse struct {
// List of results for the query
Results []SearchResult `json:"results"`
}
type SearchResult struct {
// if live broadcast then indicates activity.
// none, upcoming, live, completed
Broadcasting string `json:"broadcasting"`
// the channel id
ChannelId string `json:"channelId"`
// the channel title
ChannelTitle string `json:"channelTitle"`
// the result description
Description string `json:"description"`
// id of the result
Id string `json:"id"`
// kind of result; "video", "channel", "playlist"
Kind string `json:"kind"`
// published at time
PublishedAt string `json:"publishedAt"`
// title of the result
Title string `json:"title"`
// the associated url
Url string `json:"url"`
}

61
clients/ts/.gitignore vendored
View File

@@ -1,61 +0,0 @@
node_modules
dist
es
lib
types
tmp
index.js
index.d.ts
esm
.npmrc
esm
index.js
index.d.ts
address
answer
cache
cmd
crypto
currency
db
email
emoji
evchargers
event
file
forex
function
geocoding
gifs
google
helloworld
holidays
id
image
ip
location
mq
notes
otp
pkg
postcode
prayer
qr
quran
routing
rss
sentiment
sms
spam
stock
stream
sunnah
test
thumbnail
time
twitter
url
user
vehicle
weather
youtube

View File

@@ -1,53 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class AddressService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Lookup a list of UK addresses by postcode
lookupPostcode(
request: LookupPostcodeRequest
): Promise<LookupPostcodeResponse> {
return this.client.call(
"address",
"LookupPostcode",
request
) as Promise<LookupPostcodeResponse>;
}
}
export interface LookupPostcodeRequest {
// UK postcode e.g SW1A 2AA
postcode?: string;
}
export interface LookupPostcodeResponse {
addresses?: Record[];
}
export interface Record {
// building name
buildingName?: string;
// the county
county?: string;
// line one of address
lineOne?: string;
// line two of address
lineTwo?: string;
// dependent locality
locality?: string;
// organisation if present
organisation?: string;
// the postcode
postcode?: string;
// the premise
premise?: string;
// street name
street?: string;
// the complete address
summary?: string;
// post town
town?: string;
}

View File

@@ -1,31 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class AnswerService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Ask a question and receive an instant answer
question(request: QuestionRequest): Promise<QuestionResponse> {
return this.client.call(
"answer",
"Question",
request
) as Promise<QuestionResponse>;
}
}
export interface QuestionRequest {
// the question to answer
query?: string;
}
export interface QuestionResponse {
// the answer to your question
answer?: string;
// any related image
image?: string;
// a related url
url?: string;
}

View File

@@ -1,91 +0,0 @@
const chalk = require('chalk');
const path = require('path');
const fs = require('fs');
const rimraf = require('rimraf');
const { ncp } = require('ncp');
function getTmpEsmDirectories() {
return fs
.readdirSync('./tmp/esm')
.filter(file => fs.statSync(`./tmp/esm/${file}`).isDirectory());
}
function log(text) {
console.log(`${chalk.cyan('M3O JS:')} ${text}`);
}
function writeModulePackageJsonFile(location) {
fs.writeFileSync(
`${location}/package.json`,
`{"module": "./esm/index.js"}`,
'utf8'
);
}
function deleteDirectory(directory) {
return new Promise(resolve => {
rimraf(directory, err => {
resolve();
});
});
}
function copyAllTmpFolders() {
return new Promise((resolve, reject) => {
// Now copy to root level
ncp(path.join(__dirname, 'tmp'), __dirname, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
function moveToLocalEsmFolders() {
return new Promise((resolve, reject) => {
const esmDirs = getTmpEsmDirectories();
// Move the files around in tmp...
esmDirs.forEach(dir => {
const currentPath = path.join(__dirname, 'tmp/esm', dir);
fs.readdirSync(currentPath).forEach(async file => {
const currentFilePath = path.join(currentPath, file);
const newFilePath = path.join(__dirname, 'tmp', dir, 'esm', file);
const esmFolderLocation = path.join(__dirname, 'tmp', dir, 'esm');
try {
if (!fs.existsSync(esmFolderLocation)) {
fs.mkdirSync(esmFolderLocation);
}
fs.renameSync(currentFilePath, newFilePath);
writeModulePackageJsonFile(`./tmp/${dir}`);
await deleteDirectory(`./tmp/esm/${dir}`);
} catch (err) {
reject(err);
}
});
});
log('Moved local esm folders');
resolve();
});
}
async function build() {
log('Moving to correct folders');
try {
await moveToLocalEsmFolders();
await copyAllTmpFolders();
writeModulePackageJsonFile('./tmp/esm');
await deleteDirectory('./tmp');
} catch (e) {
console.log(e);
}
}
build();

View File

@@ -1,107 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class CacheService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Decrement a value (if it's a number)
decrement(request: DecrementRequest): Promise<DecrementResponse> {
return this.client.call(
"cache",
"Decrement",
request
) as Promise<DecrementResponse>;
}
// Delete a value from the cache
delete(request: DeleteRequest): Promise<DeleteResponse> {
return this.client.call(
"cache",
"Delete",
request
) as Promise<DeleteResponse>;
}
// Get an item from the cache by key
get(request: GetRequest): Promise<GetResponse> {
return this.client.call("cache", "Get", request) as Promise<GetResponse>;
}
// Increment a value (if it's a number)
increment(request: IncrementRequest): Promise<IncrementResponse> {
return this.client.call(
"cache",
"Increment",
request
) as Promise<IncrementResponse>;
}
// Set an item in the cache. Overwrites any existing value already set.
set(request: SetRequest): Promise<SetResponse> {
return this.client.call("cache", "Set", request) as Promise<SetResponse>;
}
}
export interface DecrementRequest {
// The key to decrement
key?: string;
// The amount to decrement the value by
value?: number;
}
export interface DecrementResponse {
// The key decremented
key?: string;
// The new value
value?: number;
}
export interface DeleteRequest {
// The key to delete
key?: string;
}
export interface DeleteResponse {
// Returns "ok" if successful
status?: string;
}
export interface GetRequest {
// The key to retrieve
key?: string;
}
export interface GetResponse {
// The key
key?: string;
// Time to live in seconds
ttl?: number;
// The value
value?: string;
}
export interface IncrementRequest {
// The key to increment
key?: string;
// The amount to increment the value by
value?: number;
}
export interface IncrementResponse {
// The key incremented
key?: string;
// The new value
value?: number;
}
export interface SetRequest {
// The key to update
key?: string;
// Time to live in seconds
ttl?: number;
// The value to set
value?: string;
}
export interface SetResponse {
// Returns "ok" if successful
status?: string;
}

View File

@@ -1,116 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class CryptoService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Returns the history for the previous close
history(request: HistoryRequest): Promise<HistoryResponse> {
return this.client.call(
"crypto",
"History",
request
) as Promise<HistoryResponse>;
}
// Get news related to a currency
news(request: NewsRequest): Promise<NewsResponse> {
return this.client.call("crypto", "News", request) as Promise<NewsResponse>;
}
// Get the last price for a given crypto ticker
price(request: PriceRequest): Promise<PriceResponse> {
return this.client.call(
"crypto",
"Price",
request
) as Promise<PriceResponse>;
}
// Get the last quote for a given crypto ticker
quote(request: QuoteRequest): Promise<QuoteResponse> {
return this.client.call(
"crypto",
"Quote",
request
) as Promise<QuoteResponse>;
}
}
export interface Article {
// the date published
date?: string;
// its description
description?: string;
// the source
source?: string;
// title of the article
title?: string;
// the source url
url?: string;
}
export interface HistoryRequest {
// the crypto symbol e.g BTCUSD
symbol?: string;
}
export interface HistoryResponse {
// the close price
close?: number;
// the date
date?: string;
// the peak price
high?: number;
// the low price
low?: number;
// the open price
open?: number;
// the crypto symbol
symbol?: string;
// the volume
volume?: number;
}
export interface NewsRequest {
// cryptocurrency ticker to request news for e.g BTC
symbol?: string;
}
export interface NewsResponse {
// list of articles
articles?: Article[];
// symbol requested for
symbol?: string;
}
export interface PriceRequest {
// the crypto symbol e.g BTCUSD
symbol?: string;
}
export interface PriceResponse {
// the last price
price?: number;
// the crypto symbol e.g BTCUSD
symbol?: string;
}
export interface QuoteRequest {
// the crypto symbol e.g BTCUSD
symbol?: string;
}
export interface QuoteResponse {
// the asking price
askPrice?: number;
// the ask size
askSize?: number;
// the bidding price
bidPrice?: number;
// the bid size
bidSize?: number;
// the crypto symbol
symbol?: string;
// the UTC timestamp of the quote
timestamp?: string;
}

View File

@@ -1,102 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class CurrencyService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Codes returns the supported currency codes for the API
codes(request: CodesRequest): Promise<CodesResponse> {
return this.client.call(
"currency",
"Codes",
request
) as Promise<CodesResponse>;
}
// Convert returns the currency conversion rate between two pairs e.g USD/GBP
convert(request: ConvertRequest): Promise<ConvertResponse> {
return this.client.call(
"currency",
"Convert",
request
) as Promise<ConvertResponse>;
}
// Returns the historic rates for a currency on a given date
history(request: HistoryRequest): Promise<HistoryResponse> {
return this.client.call(
"currency",
"History",
request
) as Promise<HistoryResponse>;
}
// Rates returns the currency rates for a given code e.g USD
rates(request: RatesRequest): Promise<RatesResponse> {
return this.client.call(
"currency",
"Rates",
request
) as Promise<RatesResponse>;
}
}
export interface Code {
// e.g United States Dollar
currency?: string;
// e.g USD
name?: string;
}
export interface CodesRequest {}
export interface CodesResponse {
codes?: Code[];
}
export interface ConvertRequest {
// optional amount to convert e.g 10.0
amount?: number;
// base code to convert from e.g USD
from?: string;
// target code to convert to e.g GBP
to?: string;
}
export interface ConvertResponse {
// converted amount e.g 7.10
amount?: number;
// the base code e.g USD
from?: string;
// conversion rate e.g 0.71
rate?: number;
// the target code e.g GBP
to?: string;
}
export interface HistoryRequest {
// currency code e.g USD
code?: string;
// date formatted as YYYY-MM-DD
date?: string;
}
export interface HistoryResponse {
// The code of the request
code?: string;
// The date requested
date?: string;
// The rate for the day as code:rate
rates?: { [key: string]: number };
}
export interface RatesRequest {
// The currency code to get rates for e.g USD
code?: string;
}
export interface RatesResponse {
// The code requested e.g USD
code?: string;
// The rates for the given code as key-value pairs code:rate
rates?: { [key: string]: number };
}

View File

@@ -1,113 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class DbService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Count records in a table
count(request: CountRequest): Promise<CountResponse> {
return this.client.call("db", "Count", request) as Promise<CountResponse>;
}
// Create a record in the database. Optionally include an "id" field otherwise it's set automatically.
create(request: CreateRequest): Promise<CreateResponse> {
return this.client.call("db", "Create", request) as Promise<CreateResponse>;
}
// Delete a record in the database by id.
delete(request: DeleteRequest): Promise<DeleteResponse> {
return this.client.call("db", "Delete", request) as Promise<DeleteResponse>;
}
// Read data from a table. Lookup can be by ID or via querying any field in the record.
read(request: ReadRequest): Promise<ReadResponse> {
return this.client.call("db", "Read", request) as Promise<ReadResponse>;
}
// Truncate the records in a table
truncate(request: TruncateRequest): Promise<TruncateResponse> {
return this.client.call(
"db",
"Truncate",
request
) as Promise<TruncateResponse>;
}
// Update a record in the database. Include an "id" in the record to update.
update(request: UpdateRequest): Promise<UpdateResponse> {
return this.client.call("db", "Update", request) as Promise<UpdateResponse>;
}
}
export interface CountRequest {
table?: string;
}
export interface CountResponse {
count?: number;
}
export interface CreateRequest {
// JSON encoded record or records (can be array or object)
record?: { [key: string]: any };
// Optional table name. Defaults to 'default'
table?: string;
}
export interface CreateResponse {
// The id of the record (either specified or automatically created)
id?: string;
}
export interface DeleteRequest {
// id of the record
id?: string;
// Optional table name. Defaults to 'default'
table?: string;
}
export interface DeleteResponse {}
export interface ReadRequest {
// Read by id. Equivalent to 'id == "your-id"'
id?: string;
// Maximum number of records to return. Default limit is 25.
// Maximum limit is 1000. Anything higher will return an error.
limit?: number;
offset?: number;
// 'asc' (default), 'desc'
order?: string;
// field name to order by
orderBy?: string;
// Examples: 'age >= 18', 'age >= 18 and verified == true'
// Comparison operators: '==', '!=', '<', '>', '<=', '>='
// Logical operator: 'and'
// Dot access is supported, eg: 'user.age == 11'
// Accessing list elements is not supported yet.
query?: string;
// Optional table name. Defaults to 'default'
table?: string;
}
export interface ReadResponse {
// JSON encoded records
records?: { [key: string]: any }[];
}
export interface TruncateRequest {
// Optional table name. Defaults to 'default'
table?: string;
}
export interface TruncateResponse {
// The table truncated
table?: string;
}
export interface UpdateRequest {
// The id of the record. If not specified it is inferred from the 'id' field of the record
id?: string;
// record, JSON object
record?: { [key: string]: any };
// Optional table name. Defaults to 'default'
table?: string;
}
export interface UpdateResponse {}

View File

@@ -1,30 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class EmailService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Send an email by passing in from, to, subject, and a text or html body
send(request: SendRequest): Promise<SendResponse> {
return this.client.call("email", "Send", request) as Promise<SendResponse>;
}
}
export interface SendRequest {
// the display name of the sender
from?: string;
// the html body
htmlBody?: string;
// an optional reply to email address
replyTo?: string;
// the email subject
subject?: string;
// the text body
textBody?: string;
// the email address of the recipient
to?: string;
}
export interface SendResponse {}

View File

@@ -1,74 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class EmojiService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Find an emoji by its alias e.g :beer:
find(request: FindRequest): Promise<FindResponse> {
return this.client.call("emoji", "Find", request) as Promise<FindResponse>;
}
// Get the flag for a country. Requires country code e.g GB for great britain
flag(request: FlagRequest): Promise<FlagResponse> {
return this.client.call("emoji", "Flag", request) as Promise<FlagResponse>;
}
// Print text and renders the emojis with aliases e.g
// let's grab a :beer: becomes let's grab a 🍺
print(request: PrintRequest): Promise<PrintResponse> {
return this.client.call(
"emoji",
"Print",
request
) as Promise<PrintResponse>;
}
// Send an emoji to anyone via SMS. Messages are sent in the form '<message> Sent from <from>'
send(request: SendRequest): Promise<SendResponse> {
return this.client.call("emoji", "Send", request) as Promise<SendResponse>;
}
}
export interface FindRequest {
// the alias code e.g :beer:
alias?: string;
}
export interface FindResponse {
// the unicode emoji 🍺
emoji?: string;
}
export interface FlagRequest {
// country code e.g GB
code?: string;
}
export interface FlagResponse {
// the emoji flag
flag?: string;
}
export interface PrintRequest {
// text including any alias e.g let's grab a :beer:
text?: string;
}
export interface PrintResponse {
// text with rendered emojis
text?: string;
}
export interface SendRequest {
// the name of the sender from e.g Alice
from?: string;
// message to send including emoji aliases
message?: string;
// phone number to send to (including international dialing code)
to?: string;
}
export interface SendResponse {
// whether or not it succeeded
success?: boolean;
}

View File

@@ -1,235 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class EvchargersService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Retrieve reference data as used by this API and in conjunction with the Search endpoint
referenceData(request: ReferenceDataRequest): Promise<ReferenceDataResponse> {
return this.client.call(
"evchargers",
"ReferenceData",
request
) as Promise<ReferenceDataResponse>;
}
// Search by giving a coordinate and a max distance, or bounding box and optional filters
search(request: SearchRequest): Promise<SearchResponse> {
return this.client.call(
"evchargers",
"Search",
request
) as Promise<SearchResponse>;
}
}
export interface Address {
// Any comments about how to access the charger
accessComments?: string;
addressLine1?: string;
addressLine2?: string;
country?: { [key: string]: any };
countryId?: string;
latLng?: string;
location?: Coordinates;
postcode?: string;
stateOrProvince?: string;
title?: string;
town?: string;
}
export interface BoundingBox {
bottomLeft?: Coordinates;
topRight?: Coordinates;
}
export interface ChargerType {
comments?: string;
id?: string;
// Is this 40KW+
isFastChargeCapable?: boolean;
title?: string;
}
export interface CheckinStatusType {
id?: string;
isAutomated?: boolean;
isPositive?: boolean;
title?: string;
}
export interface Connection {
// The amps offered
amps?: number;
connectionType?: ConnectionType;
// The ID of the connection type
connectionTypeId?: string;
// The current
current?: string;
level?: ChargerType;
// The level of charging power available
levelId?: string;
// The power in KW
power?: number;
reference?: string;
// The voltage offered
voltage?: number;
}
export interface ConnectionType {
formalName?: string;
id?: string;
isDiscontinued?: boolean;
isObsolete?: boolean;
title?: string;
}
export interface Coordinates {
latitude?: number;
longitude?: number;
}
export interface Country {
continentCode?: string;
id?: string;
isoCode?: string;
title?: string;
}
export interface CurrentType {
description?: string;
id?: string;
title?: string;
}
export interface DataProvider {
comments?: string;
dataProviderStatusType?: DataProviderStatusType;
id?: string;
// How is this data licensed
license?: string;
title?: string;
website?: string;
}
export interface DataProviderStatusType {
id?: string;
isProviderEnabled?: boolean;
title?: string;
}
export interface Operator {
comments?: string;
contactEmail?: string;
faultReportEmail?: string;
id?: string;
// Is this operator a private individual vs a company
isPrivateIndividual?: boolean;
phonePrimary?: string;
phoneSecondary?: string;
title?: string;
website?: string;
}
export interface Poi {
// The address
address?: { [key: string]: any };
// The connections available at this charge point
connections?: Connection[];
// The cost of charging
cost?: string;
// The ID of the data provider
dataProviderId?: string;
// The ID of the charger
id?: string;
// The number of charging points
numPoints?: number;
// The operator
operator?: { [key: string]: any };
// The ID of the operator of the charger
operatorId?: string;
// The type of usage
usageType?: UsageType;
// The type of usage for this charger point (is it public, membership required, etc)
usageTypeId?: string;
}
export interface ReferenceDataRequest {}
export interface ReferenceDataResponse {
// The types of charger
chargerTypes?: ChargerType;
// The types of checkin status
checkinStatusTypes?: CheckinStatusType;
// The types of connection
connectionTypes?: ConnectionType;
// The countries
countries?: Country[];
// The types of current
currentTypes?: CurrentType;
// The providers of the charger data
dataProviders?: DataProvider;
// The companies operating the chargers
operators?: Operator[];
// The status of the charger
statusTypes?: StatusType;
// The status of a submission
submissionStatusTypes?: SubmissionStatusType;
// The different types of usage
usageTypes?: UsageType;
// The types of user comment
userCommentTypes?: UserCommentType;
}
export interface SearchRequest {
// Bounding box to search within (top left and bottom right coordinates)
box?: BoundingBox;
// IDs of the connection type
connectionTypes?: string;
// Country ID
countryId?: string;
// Search distance from point in metres, defaults to 5000m
distance?: number;
// Supported charging levels
levels?: string[];
// Coordinates from which to begin search
location?: Coordinates;
// Maximum number of results to return, defaults to 100
maxResults?: number;
// Minimum power in KW. Note: data not available for many chargers
minPower?: number;
// IDs of the the EV charger operator
operators?: string[];
// Usage of the charge point (is it public, membership required, etc)
usageTypes?: string;
}
export interface SearchResponse {
pois?: Poi[];
}
export interface StatusType {
id?: string;
isOperational?: boolean;
title?: string;
}
export interface SubmissionStatusType {
id?: string;
isLive?: boolean;
title?: string;
}
export interface UsageType {
id?: string;
isAccessKeyRequired?: boolean;
isMembershipRequired?: boolean;
isPayAtLocation?: boolean;
title?: string;
}
export interface UserCommentType {
id?: string;
title?: string;
}

View File

@@ -1,92 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class FileService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Delete a file by project name/path
delete(request: DeleteRequest): Promise<DeleteResponse> {
return this.client.call(
"file",
"Delete",
request
) as Promise<DeleteResponse>;
}
// List files by their project and optionally a path.
list(request: ListRequest): Promise<ListResponse> {
return this.client.call("file", "List", request) as Promise<ListResponse>;
}
// Read a file by path
read(request: ReadRequest): Promise<ReadResponse> {
return this.client.call("file", "Read", request) as Promise<ReadResponse>;
}
// Save a file
save(request: SaveRequest): Promise<SaveResponse> {
return this.client.call("file", "Save", request) as Promise<SaveResponse>;
}
}
export interface BatchSaveRequest {
files?: Record[];
}
export interface BatchSaveResponse {}
export interface DeleteRequest {
// Path to the file
path?: string;
// The project name
project?: string;
}
export interface DeleteResponse {}
export interface ListRequest {
// Defaults to '/', ie. lists all files in a project.
// Supply path to a folder if you want to list
// files inside that folder
// eg. '/docs'
path?: string;
// Project, required for listing.
project?: string;
}
export interface ListResponse {
files?: Record[];
}
export interface ReadRequest {
// Path to the file
path?: string;
// Project name
project?: string;
}
export interface ReadResponse {
// Returns the file
file?: Record;
}
export interface Record {
// File contents
content?: string;
// Time the file was created e.g 2021-05-20T13:37:21Z
created?: string;
// Any other associated metadata as a map of key-value pairs
metadata?: { [key: string]: string };
// Path to file or folder eg. '/documents/text-files/file.txt'.
path?: string;
// A custom project to group files
// eg. file-of-mywebsite.com
project?: string;
// Time the file was updated e.g 2021-05-20T13:37:21Z
updated?: string;
}
export interface SaveRequest {
file?: Record;
}
export interface SaveResponse {}

View File

@@ -1,83 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class ForexService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Returns the data for the previous close
history(request: HistoryRequest): Promise<HistoryResponse> {
return this.client.call(
"forex",
"History",
request
) as Promise<HistoryResponse>;
}
// Get the latest price for a given forex ticker
price(request: PriceRequest): Promise<PriceResponse> {
return this.client.call(
"forex",
"Price",
request
) as Promise<PriceResponse>;
}
// Get the latest quote for the forex
quote(request: QuoteRequest): Promise<QuoteResponse> {
return this.client.call(
"forex",
"Quote",
request
) as Promise<QuoteResponse>;
}
}
export interface HistoryRequest {
// the forex symbol e.g GBPUSD
symbol?: string;
}
export interface HistoryResponse {
// the close price
close?: number;
// the date
date?: string;
// the peak price
high?: number;
// the low price
low?: number;
// the open price
open?: number;
// the forex symbol
symbol?: string;
// the volume
volume?: number;
}
export interface PriceRequest {
// forex symbol e.g GBPUSD
symbol?: string;
}
export interface PriceResponse {
// the last price
price?: number;
// the forex symbol e.g GBPUSD
symbol?: string;
}
export interface QuoteRequest {
// the forex symbol e.g GBPUSD
symbol?: string;
}
export interface QuoteResponse {
// the asking price
askPrice?: number;
// the bidding price
bidPrice?: number;
// the forex symbol
symbol?: string;
// the UTC timestamp of the quote
timestamp?: string;
}

View File

@@ -1,146 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class FunctionService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Call a function by name
call(request: CallRequest): Promise<CallResponse> {
return this.client.call(
"function",
"Call",
request
) as Promise<CallResponse>;
}
// Delete a function by name
delete(request: DeleteRequest): Promise<DeleteResponse> {
return this.client.call(
"function",
"Delete",
request
) as Promise<DeleteResponse>;
}
// Deploy a group of functions
deploy(request: DeployRequest): Promise<DeployResponse> {
return this.client.call(
"function",
"Deploy",
request
) as Promise<DeployResponse>;
}
//
describe(request: DescribeRequest): Promise<DescribeResponse> {
return this.client.call(
"function",
"Describe",
request
) as Promise<DescribeResponse>;
}
// List all the deployed functions
list(request: ListRequest): Promise<ListResponse> {
return this.client.call(
"function",
"List",
request
) as Promise<ListResponse>;
}
}
export interface CallRequest {
// Name of the function
name?: string;
// Request body that will be passed to the function
request?: { [key: string]: any };
}
export interface CallResponse {
// Response body that the function returned
response?: { [key: string]: any };
}
export interface DeleteRequest {
// The name of the function
name?: string;
// Optional project name
project?: string;
}
export interface DeleteResponse {}
export interface DeployRequest {
// entry point, ie. handler name in the source code
// if not provided, defaults to the name parameter
entrypoint?: string;
// function name
name?: string;
// project is used for namespacing your functions
// optional. defaults to "default".
project?: string;
// github url to repo
repo?: string;
// runtime/language of the function
// eg: php74,
// nodejs6, nodejs8, nodejs10, nodejs12, nodejs14, nodejs16
// dotnet3
// java11
// ruby26, ruby27
// go111, go113, go116
// python37, python38, python39
runtime?: string;
// optional subfolder path
subfolder?: string;
}
export interface DeployResponse {}
export interface DescribeRequest {
// The name of the function
name?: string;
// Optional project name
project?: string;
}
export interface DescribeResponse {
status?: string;
timeout?: string;
updateTime?: string;
}
export interface Func {
// name of handler in source code
entrypoint?: string;
// function name
// limitation: must be unique across projects
name?: string;
// project of function, optional
// defaults to literal "default"
// used to namespace functions
project?: string;
// git repo address
repo?: string;
// runtime/language of the function
// eg: php74,
// nodejs6, nodejs8, nodejs10, nodejs12, nodejs14, nodejs16
// dotnet3
// java11
// ruby26, ruby27
// go111, go113, go116
// python37, python38, python39
runtime?: string;
// eg. ACTIVE, DEPLOY_IN_PROGRESS, OFFLINE etc
status?: string;
// subfolder path to entrypoint
subfolder?: string;
}
export interface ListRequest {
// optional project name
project?: string;
}
export interface ListResponse {
// List of functions deployed
functions?: Func[];
}

View File

@@ -1,60 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class GeocodingService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Lookup returns a geocoded address including normalized address and gps coordinates. All fields are optional, provide more to get more accurate results
lookup(request: LookupRequest): Promise<LookupResponse> {
return this.client.call(
"geocoding",
"Lookup",
request
) as Promise<LookupResponse>;
}
// Reverse lookup an address from gps coordinates
reverse(request: ReverseRequest): Promise<ReverseResponse> {
return this.client.call(
"geocoding",
"Reverse",
request
) as Promise<ReverseResponse>;
}
}
export interface Address {
city?: string;
country?: string;
lineOne?: string;
lineTwo?: string;
postcode?: string;
}
export interface Location {
latitude?: number;
longitude?: number;
}
export interface LookupRequest {
address?: string;
city?: string;
country?: string;
postcode?: string;
}
export interface LookupResponse {
address?: { [key: string]: any };
location?: { [key: string]: any };
}
export interface ReverseRequest {
latitude?: number;
longitude?: number;
}
export interface ReverseResponse {
address?: { [key: string]: any };
location?: { [key: string]: any };
}

View File

@@ -1,129 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class GifsService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Search for a gif
search(request: SearchRequest): Promise<SearchResponse> {
return this.client.call(
"gifs",
"Search",
request
) as Promise<SearchResponse>;
}
}
export interface Gif {
// URL used for embedding the GIF
embedUrl?: string;
// The ID of the GIF
id?: string;
// The different formats available for this GIF
images?: ImageFormats;
// The content rating for the GIF
rating?: string;
// A short URL for this GIF
shortUrl?: string;
// The slug used in the GIF's URL
slug?: string;
// The page on which this GIF was found
source?: string;
// The title for this GIF
title?: string;
// The URL for this GIF
url?: string;
}
export interface ImageFormat {
// height
height?: number;
// size of the MP4 version
mp4Size?: number;
// URL to an MP4 version of the gif
mp4Url?: string;
// size in bytes
size?: number;
// URL of the gif
url?: string;
// size of the webp version
webpSize?: number;
// URL to a webp version of the gif
webpUrl?: string;
// width
width?: number;
}
export interface ImageFormats {
// A downsized version of the GIF < 2MB
downsized?: ImageFormat;
// A downsized version of the GIF < 8MB
downsizedLarge?: ImageFormat;
// A downsized version of the GIF < 5MB
downsizedMedium?: ImageFormat;
// A downsized version of the GIF < 200kb
downsizedSmall?: ImageFormat;
// Static image of the downsized version of the GIF
downsizedStill?: ImageFormat;
// Version of the GIF with fixed height of 200 pixels. Good for mobile use
fixedHeight?: ImageFormat;
// Version of the GIF with fixed height of 200 pixels and number of frames reduced to 6
fixedHeightDownsampled?: ImageFormat;
// Version of the GIF with fixed height of 100 pixels. Good for mobile keyboards
fixedHeightSmall?: ImageFormat;
// Static image of the GIF with fixed height of 100 pixels
fixedHeightSmallStill?: ImageFormat;
// Static image of the GIF with fixed height of 200 pixels
fixedHeightStill?: ImageFormat;
// Version of the GIF with fixed width of 200 pixels. Good for mobile use
fixedWidth?: ImageFormat;
// Version of the GIF with fixed width of 200 pixels and number of frames reduced to 6
fixedWidthDownsampled?: ImageFormat;
// Version of the GIF with fixed width of 100 pixels. Good for mobile keyboards
fixedWidthSmall?: ImageFormat;
// Static image of the GIF with fixed width of 100 pixels
fixedWidthSmallStill?: ImageFormat;
// Static image of the GIF with fixed width of 200 pixels
fixedWidthStill?: ImageFormat;
// 15 second version of the GIF looping
looping?: ImageFormat;
// The original GIF. Good for desktop use
original?: ImageFormat;
// Static image of the original version of the GIF
originalStill?: ImageFormat;
// mp4 version of the GIF <50kb displaying first 1-2 secs
preview?: ImageFormat;
// Version of the GIF <50kb displaying first 1-2 secs
previewGif?: ImageFormat;
}
export interface Pagination {
// total number returned in this response
count?: number;
// position in pagination
offset?: number;
// total number of results available
totalCount?: number;
}
export interface SearchRequest {
// ISO 2 letter language code for regional content
lang?: string;
// Max number of gifs to return. Defaults to 25
limit?: number;
// The start position of results (used with pagination)
offset?: number;
// The search term
query?: string;
// Apply age related content filter. "g", "pg", "pg-13", or "r". Defaults to "g"
rating?: string;
}
export interface SearchResponse {
// list of results
data?: Gif[];
// information on pagination
pagination?: { [key: string]: any };
}

View File

@@ -1,43 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class HelloworldService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Call returns a personalised "Hello $name" response
call(request: CallRequest): Promise<CallResponse> {
return this.client.call(
"helloworld",
"Call",
request
) as Promise<CallResponse>;
}
// Stream returns a stream of "Hello $name" responses
stream(request: StreamRequest): Promise<StreamResponse> {
return this.client.call(
"helloworld",
"Stream",
request
) as Promise<StreamResponse>;
}
}
export interface CallRequest {
name?: string;
}
export interface CallResponse {
message?: string;
}
export interface StreamRequest {
// the number of messages to send back
messages?: number;
name?: string;
}
export interface StreamResponse {
message?: string;
}

View File

@@ -1,64 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class HolidaysService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Get the list of countries that are supported by this API
countries(request: CountriesRequest): Promise<CountriesResponse> {
return this.client.call(
"holidays",
"Countries",
request
) as Promise<CountriesResponse>;
}
// List the holiday dates for a given country and year
list(request: ListRequest): Promise<ListResponse> {
return this.client.call(
"holidays",
"List",
request
) as Promise<ListResponse>;
}
}
export interface CountriesRequest {}
export interface CountriesResponse {
countries?: Country[];
}
export interface Country {
// The 2 letter country code (as defined in ISO 3166-1 alpha-2)
code?: string;
// The English name of the country
name?: string;
}
export interface Holiday {
// the country this holiday occurs in
countryCode?: string;
// date of the holiday in yyyy-mm-dd format
date?: string;
// the local name of the holiday
localName?: string;
// the name of the holiday in English
name?: string;
// the regions within the country that observe this holiday (if not all of them)
regions?: string[];
// the type of holiday Public, Bank, School, Authorities, Optional, Observance
types?: string[];
}
export interface ListRequest {
// The 2 letter country code (as defined in ISO 3166-1 alpha-2)
countryCode?: string;
// The year to list holidays for
year?: number;
}
export interface ListResponse {
holidays?: Holiday[];
}

View File

@@ -1,39 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class IdService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Generate a unique ID. Defaults to uuid.
generate(request: GenerateRequest): Promise<GenerateResponse> {
return this.client.call(
"id",
"Generate",
request
) as Promise<GenerateResponse>;
}
// List the types of IDs available. No query params needed.
types(request: TypesRequest): Promise<TypesResponse> {
return this.client.call("id", "Types", request) as Promise<TypesResponse>;
}
}
export interface GenerateRequest {
// type of id e.g uuid, shortid, snowflake (64 bit), bigflake (128 bit)
type?: string;
}
export interface GenerateResponse {
// the unique id generated
id?: string;
// the type of id generated
type?: string;
}
export interface TypesRequest {}
export interface TypesResponse {
types?: string[];
}

View File

@@ -1,113 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class ImageService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Convert an image from one format (jpeg, png etc.) to an other either on the fly (from base64 to base64),
// or by uploading the conversion result.
convert(request: ConvertRequest): Promise<ConvertResponse> {
return this.client.call(
"image",
"Convert",
request
) as Promise<ConvertResponse>;
}
// Resize an image on the fly without storing it (by sending and receiving a base64 encoded image), or resize and upload depending on parameters.
// If one of width or height is 0, the image aspect ratio is preserved.
// Optional cropping.
resize(request: ResizeRequest): Promise<ResizeResponse> {
return this.client.call(
"image",
"Resize",
request
) as Promise<ResizeResponse>;
}
// Upload an image by either sending a base64 encoded image to this endpoint or a URL.
// To resize an image before uploading, see the Resize endpoint.
upload(request: UploadRequest): Promise<UploadResponse> {
return this.client.call(
"image",
"Upload",
request
) as Promise<UploadResponse>;
}
}
export interface ConvertRequest {
// base64 encoded image to resize,
// ie. "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
base64?: string;
// output name of the image including extension, ie. "cat.png"
name?: string;
// make output a URL and not a base64 response
outputURL?: boolean;
// url of the image to resize
url?: string;
}
export interface ConvertResponse {
base64?: string;
url?: string;
}
export interface CropOptions {
// Crop anchor point: "top", "top left", "top right",
// "left", "center", "right"
// "bottom left", "bottom", "bottom right".
// Optional. Defaults to center.
anchor?: string;
// height to crop to
height?: number;
// width to crop to
width?: number;
}
export interface Point {
x?: number;
y?: number;
}
export interface Rectangle {
max?: Point;
min?: Point;
}
export interface ResizeRequest {
// base64 encoded image to resize,
// ie. "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
base64?: string;
// optional crop options
// if provided, after resize, the image
// will be cropped
cropOptions?: CropOptions;
height?: number;
// output name of the image including extension, ie. "cat.png"
name?: string;
// make output a URL and not a base64 response
outputURL?: boolean;
// url of the image to resize
url?: string;
width?: number;
}
export interface ResizeResponse {
base64?: string;
url?: string;
}
export interface UploadRequest {
// Base64 encoded image to upload,
// ie. "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
base64?: string;
// Output name of the image including extension, ie. "cat.png"
name?: string;
// URL of the image to upload
url?: string;
}
export interface UploadResponse {
url?: string;
}

View File

@@ -1,141 +0,0 @@
import * as address from "./address";
import * as answer from "./answer";
import * as cache from "./cache";
import * as crypto from "./crypto";
import * as currency from "./currency";
import * as db from "./db";
import * as email from "./email";
import * as emoji from "./emoji";
import * as evchargers from "./evchargers";
import * as event from "./event";
import * as file from "./file";
import * as forex from "./forex";
import * as fx from "./function";
import * as geocoding from "./geocoding";
import * as gifs from "./gifs";
import * as google from "./google";
import * as helloworld from "./helloworld";
import * as holidays from "./holidays";
import * as id from "./id";
import * as image from "./image";
import * as ip from "./ip";
import * as location from "./location";
import * as mq from "./mq";
import * as notes from "./notes";
import * as otp from "./otp";
import * as postcode from "./postcode";
import * as prayer from "./prayer";
import * as qr from "./qr";
import * as quran from "./quran";
import * as routing from "./routing";
import * as rss from "./rss";
import * as sentiment from "./sentiment";
import * as sms from "./sms";
import * as spam from "./spam";
import * as stock from "./stock";
import * as stream from "./stream";
import * as sunnah from "./sunnah";
import * as thumbnail from "./thumbnail";
import * as time from "./time";
import * as twitter from "./twitter";
import * as url from "./url";
import * as user from "./user";
import * as vehicle from "./vehicle";
import * as weather from "./weather";
import * as youtube from "./youtube";
export class Client {
constructor(token: string) {
this.addressService = new address.AddressService(token);
this.answerService = new answer.AnswerService(token);
this.cacheService = new cache.CacheService(token);
this.cryptoService = new crypto.CryptoService(token);
this.currencyService = new currency.CurrencyService(token);
this.dbService = new db.DbService(token);
this.emailService = new email.EmailService(token);
this.emojiService = new emoji.EmojiService(token);
this.evchargersService = new evchargers.EvchargersService(token);
this.eventService = new event.EventService(token);
this.fileService = new file.FileService(token);
this.forexService = new forex.ForexService(token);
this.functionService = new fx.FunctionService(token);
this.geocodingService = new geocoding.GeocodingService(token);
this.gifsService = new gifs.GifsService(token);
this.googleService = new google.GoogleService(token);
this.helloworldService = new helloworld.HelloworldService(token);
this.holidaysService = new holidays.HolidaysService(token);
this.idService = new id.IdService(token);
this.imageService = new image.ImageService(token);
this.ipService = new ip.IpService(token);
this.locationService = new location.LocationService(token);
this.mqService = new mq.MqService(token);
this.notesService = new notes.NotesService(token);
this.otpService = new otp.OtpService(token);
this.postcodeService = new postcode.PostcodeService(token);
this.prayerService = new prayer.PrayerService(token);
this.qrService = new qr.QrService(token);
this.quranService = new quran.QuranService(token);
this.routingService = new routing.RoutingService(token);
this.rssService = new rss.RssService(token);
this.sentimentService = new sentiment.SentimentService(token);
this.smsService = new sms.SmsService(token);
this.spamService = new spam.SpamService(token);
this.stockService = new stock.StockService(token);
this.streamService = new stream.StreamService(token);
this.sunnahService = new sunnah.SunnahService(token);
this.thumbnailService = new thumbnail.ThumbnailService(token);
this.timeService = new time.TimeService(token);
this.twitterService = new twitter.TwitterService(token);
this.urlService = new url.UrlService(token);
this.userService = new user.UserService(token);
this.vehicleService = new vehicle.VehicleService(token);
this.weatherService = new weather.WeatherService(token);
this.youtubeService = new youtube.YoutubeService(token);
}
addressService: address.AddressService;
answerService: answer.AnswerService;
cacheService: cache.CacheService;
cryptoService: crypto.CryptoService;
currencyService: currency.CurrencyService;
dbService: db.DbService;
emailService: email.EmailService;
emojiService: emoji.EmojiService;
evchargersService: evchargers.EvchargersService;
eventService: event.EventService;
fileService: file.FileService;
forexService: forex.ForexService;
functionService: fx.FunctionService;
geocodingService: geocoding.GeocodingService;
gifsService: gifs.GifsService;
googleService: google.GoogleService;
helloworldService: helloworld.HelloworldService;
holidaysService: holidays.HolidaysService;
idService: id.IdService;
imageService: image.ImageService;
ipService: ip.IpService;
locationService: location.LocationService;
mqService: mq.MqService;
notesService: notes.NotesService;
otpService: otp.OtpService;
postcodeService: postcode.PostcodeService;
prayerService: prayer.PrayerService;
qrService: qr.QrService;
quranService: quran.QuranService;
routingService: routing.RoutingService;
rssService: rss.RssService;
sentimentService: sentiment.SentimentService;
smsService: sms.SmsService;
spamService: spam.SpamService;
stockService: stock.StockService;
streamService: stream.StreamService;
sunnahService: sunnah.SunnahService;
thumbnailService: thumbnail.ThumbnailService;
timeService: time.TimeService;
twitterService: twitter.TwitterService;
urlService: url.UrlService;
userService: user.UserService;
vehicleService: vehicle.VehicleService;
weatherService: weather.WeatherService;
youtubeService: youtube.YoutubeService;
}

View File

@@ -1,37 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class IpService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Lookup the geolocation information for an IP address
lookup(request: LookupRequest): Promise<LookupResponse> {
return this.client.call("ip", "Lookup", request) as Promise<LookupResponse>;
}
}
export interface LookupRequest {
// IP to lookup
ip?: string;
}
export interface LookupResponse {
// Autonomous system number
asn?: number;
// Name of the city
city?: string;
// Name of the continent
continent?: string;
// Name of the country
country?: string;
// IP of the query
ip?: string;
// Latitude e.g 52.523219
latitude?: number;
// Longitude e.g 13.428555
longitude?: number;
// Timezone e.g Europe/Rome
timezone?: string;
}

View File

@@ -1,75 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class LocationService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Read an entity by its ID
read(request: ReadRequest): Promise<ReadResponse> {
return this.client.call(
"location",
"Read",
request
) as Promise<ReadResponse>;
}
// Save an entity's current position
save(request: SaveRequest): Promise<SaveResponse> {
return this.client.call(
"location",
"Save",
request
) as Promise<SaveResponse>;
}
// Search for entities in a given radius
search(request: SearchRequest): Promise<SearchResponse> {
return this.client.call(
"location",
"Search",
request
) as Promise<SearchResponse>;
}
}
export interface Entity {
id?: string;
location?: Point;
type?: string;
}
export interface Point {
latitude?: number;
longitude?: number;
timestamp?: number;
}
export interface ReadRequest {
// the entity id
id?: string;
}
export interface ReadResponse {
entity?: { [key: string]: any };
}
export interface SaveRequest {
entity?: { [key: string]: any };
}
export interface SaveResponse {}
export interface SearchRequest {
// Central position to search from
center?: Point;
// Maximum number of entities to return
numEntities?: number;
// radius in meters
radius?: number;
// type of entities to filter
type?: string;
}
export interface SearchResponse {
entities?: Entity[];
}

View File

@@ -1,120 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class NotesService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Create a new note
create(request: CreateRequest): Promise<CreateResponse> {
return this.client.call(
"notes",
"Create",
request
) as Promise<CreateResponse>;
}
// Delete a note
delete(request: DeleteRequest): Promise<DeleteResponse> {
return this.client.call(
"notes",
"Delete",
request
) as Promise<DeleteResponse>;
}
// List all the notes
list(request: ListRequest): Promise<ListResponse> {
return this.client.call("notes", "List", request) as Promise<ListResponse>;
}
// Read a note
read(request: ReadRequest): Promise<ReadResponse> {
return this.client.call("notes", "Read", request) as Promise<ReadResponse>;
}
// Specify the note to events
subscribe(request: SubscribeRequest): Promise<SubscribeResponse> {
return this.client.call(
"notes",
"Subscribe",
request
) as Promise<SubscribeResponse>;
}
// Update a note
update(request: UpdateRequest): Promise<UpdateResponse> {
return this.client.call(
"notes",
"Update",
request
) as Promise<UpdateResponse>;
}
}
export interface CreateRequest {
// note text
text?: string;
// note title
title?: string;
}
export interface CreateResponse {
// The created note
note?: { [key: string]: any };
}
export interface DeleteRequest {
// specify the id of the note
id?: string;
}
export interface DeleteResponse {
note?: { [key: string]: any };
}
export interface ListRequest {}
export interface ListResponse {
// the list of notes
notes?: Note[];
}
export interface Note {
// time at which the note was created
created?: string;
// unique id for the note, generated if not specified
id?: string;
// text within the note
text?: string;
// title of the note
title?: string;
// time at which the note was updated
updated?: string;
}
export interface ReadRequest {
// the note id
id?: string;
}
export interface ReadResponse {
// The note
note?: { [key: string]: any };
}
export interface SubscribeRequest {
// optionally specify a note id
id?: string;
}
export interface SubscribeResponse {
// the event which occured; created, deleted, updated
event?: string;
// the note which the operation occured on
note?: { [key: string]: any };
}
export interface UpdateRequest {
note?: { [key: string]: any };
}
export interface UpdateResponse {
note?: { [key: string]: any };
}

View File

@@ -1,51 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class OtpService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Generate an OTP (one time pass) code
generate(request: GenerateRequest): Promise<GenerateResponse> {
return this.client.call(
"otp",
"Generate",
request
) as Promise<GenerateResponse>;
}
// Validate the OTP code
validate(request: ValidateRequest): Promise<ValidateResponse> {
return this.client.call(
"otp",
"Validate",
request
) as Promise<ValidateResponse>;
}
}
export interface GenerateRequest {
// expiration in seconds (default: 60)
expiry?: number;
// unique id, email or user to generate an OTP for
id?: string;
// number of characters (default: 6)
size?: number;
}
export interface GenerateResponse {
// one time pass code
code?: string;
}
export interface ValidateRequest {
// one time pass code to validate
code?: string;
// unique id, email or user for which the code was generated
id?: string;
}
export interface ValidateResponse {
// returns true if the code is valid for the ID
success?: boolean;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,83 +0,0 @@
{
"author": "",
"dependencies": {
"@m3o/m3o-node": "^0.0.24",
"@types/estree": "^0.0.47",
"chalk": "^2.4.2",
"move-file": "^3.0.0",
"ncp": "^2.0.0",
"rimraf": "^3.0.2"
},
"devDependencies": {
"prettier": "^2.4.1",
"typescript": "^3.5.1"
},
"files": [
"esm",
"index.js",
"index.d.ts",
"address",
"answer",
"cache",
"cmd",
"crypto",
"currency",
"db",
"email",
"emoji",
"evchargers",
"event",
"file",
"forex",
"function",
"geocoding",
"gifs",
"google",
"helloworld",
"holidays",
"id",
"image",
"ip",
"location",
"mq",
"notes",
"otp",
"pkg",
"postcode",
"prayer",
"qr",
"quran",
"routing",
"rss",
"sentiment",
"sms",
"spam",
"stock",
"stream",
"sunnah",
"test",
"thumbnail",
"time",
"twitter",
"url",
"user",
"vehicle",
"weather",
"youtube"
],
"license": "ISC",
"main": "index.js",
"module": "esm/index.js",
"name": "m3o",
"repository": {
"type": "git",
"url": "https://github.com/m3o/m3o-js"
},
"scripts": {
"build": "npm run clean \u0026\u0026 tsc \u0026\u0026 tsc --p tsconfig.es.json \u0026\u0026 node build.js",
"clean": "rimraf ./tmp",
"prepare": "npm run build"
},
"types": "index.d.ts",
"version": "1.0.770"
}

View File

@@ -1,84 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class PostcodeService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Lookup a postcode to retrieve the related region, county, etc
lookup(request: LookupRequest): Promise<LookupResponse> {
return this.client.call(
"postcode",
"Lookup",
request
) as Promise<LookupResponse>;
}
// Return a random postcode and its related info
random(request: RandomRequest): Promise<RandomResponse> {
return this.client.call(
"postcode",
"Random",
request
) as Promise<RandomResponse>;
}
// Validate a postcode.
validate(request: ValidateRequest): Promise<ValidateResponse> {
return this.client.call(
"postcode",
"Validate",
request
) as Promise<ValidateResponse>;
}
}
export interface LookupRequest {
// UK postcode e.g SW1A 2AA
postcode?: string;
}
export interface LookupResponse {
// country e.g United Kingdom
country?: string;
// e.g Westminster
district?: string;
// e.g 51.50354
latitude?: number;
// e.g -0.127695
longitude?: number;
// UK postcode e.g SW1A 2AA
postcode?: string;
// related region e.g London
region?: string;
// e.g St James's
ward?: string;
}
export interface RandomRequest {}
export interface RandomResponse {
// country e.g United Kingdom
country?: string;
// e.g Westminster
district?: string;
// e.g 51.50354
latitude?: number;
// e.g -0.127695
longitude?: number;
// UK postcode e.g SW1A 2AA
postcode?: string;
// related region e.g London
region?: string;
// e.g St James's
ward?: string;
}
export interface ValidateRequest {
// UK postcode e.g SW1A 2AA
postcode?: string;
}
export interface ValidateResponse {
// Is the postcode valid (true) or not (false)
valid?: boolean;
}

View File

@@ -1,63 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class PrayerService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Get the prayer (salah) times for a location on a given date
times(request: TimesRequest): Promise<TimesResponse> {
return this.client.call(
"prayer",
"Times",
request
) as Promise<TimesResponse>;
}
}
export interface PrayerTime {
// asr time
asr?: string;
// date for prayer times in YYYY-MM-DD format
date?: string;
// fajr time
fajr?: string;
// isha time
isha?: string;
// maghrib time
maghrib?: string;
// time of sunrise
sunrise?: string;
// zuhr time
zuhr?: string;
}
export interface TimesRequest {
// optional date in YYYY-MM-DD format, otherwise uses today
date?: string;
// number of days to request times for
days?: number;
// optional latitude used in place of location
latitude?: number;
// location to retrieve prayer times for.
// this can be a specific address, city, etc
location?: string;
// optional longitude used in place of location
longitude?: number;
}
export interface TimesResponse {
// date of request
date?: string;
// number of days
days?: number;
// latitude of location
latitude?: number;
// location for the request
location?: string;
// longitude of location
longitude?: number;
// prayer times for the given location
times?: PrayerTime[];
}

View File

@@ -1,29 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class QrService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Generate a QR code with a specific text and size
generate(request: GenerateRequest): Promise<GenerateResponse> {
return this.client.call(
"qr",
"Generate",
request
) as Promise<GenerateResponse>;
}
}
export interface GenerateRequest {
// the size (height and width) in pixels of the generated QR code. Defaults to 256
size?: number;
// the text to encode as a QR code (URL, phone number, email, etc)
text?: string;
}
export interface GenerateResponse {
// link to the QR code image in PNG format
qr?: string;
}

View File

@@ -1,218 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class QuranService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// List the Chapters (surahs) of the Quran
chapters(request: ChaptersRequest): Promise<ChaptersResponse> {
return this.client.call(
"quran",
"Chapters",
request
) as Promise<ChaptersResponse>;
}
// Search the Quran for any form of query or questions
search(request: SearchRequest): Promise<SearchResponse> {
return this.client.call(
"quran",
"Search",
request
) as Promise<SearchResponse>;
}
// Get a summary for a given chapter (surah)
summary(request: SummaryRequest): Promise<SummaryResponse> {
return this.client.call(
"quran",
"Summary",
request
) as Promise<SummaryResponse>;
}
// Lookup the verses (ayahs) for a chapter including
// translation, interpretation and breakdown by individual
// words.
verses(request: VersesRequest): Promise<VersesResponse> {
return this.client.call(
"quran",
"Verses",
request
) as Promise<VersesResponse>;
}
}
export interface Chapter {
// The arabic name of the chapter
arabicName?: string;
// The complex name of the chapter
complexName?: string;
// The id of the chapter as a number e.g 1
id?: number;
// The simple name of the chapter
name?: string;
// The pages from and to e.g 1, 1
pages?: number[];
// Should the chapter start with bismillah
prefixBismillah?: boolean;
// The order in which it was revealed
revelationOrder?: number;
// The place of revelation
revelationPlace?: string;
// The translated name
translatedName?: string;
// The number of verses in the chapter
verses?: number;
}
export interface ChaptersRequest {
// Specify the language e.g en
language?: string;
}
export interface ChaptersResponse {
chapters?: Chapter[];
}
export interface Interpretation {
// The unique id of the interpretation
id?: number;
// The source of the interpretation
source?: string;
// The translated text
text?: string;
}
export interface Result {
// The associated arabic text
text?: string;
// The related translations to the text
translations?: Translation[];
// The unique verse id across the Quran
verseId?: number;
// The verse key e.g 1:1
verseKey?: string;
}
export interface SearchRequest {
// The language for translation
language?: string;
// The number of results to return
limit?: number;
// The pagination number
page?: number;
// The query to ask
query?: string;
}
export interface SearchResponse {
// The current page
page?: number;
// The question asked
query?: string;
// The results for the query
results?: Result[];
// The total pages
totalPages?: number;
// The total results returned
totalResults?: number;
}
export interface SummaryRequest {
// The chapter id e.g 1
chapter?: number;
// Specify the language e.g en
language?: string;
}
export interface SummaryResponse {
// The chapter id
chapter?: number;
// The source of the summary
source?: string;
// The short summary for the chapter
summary?: string;
// The full description for the chapter
text?: string;
}
export interface Translation {
// The unique id of the translation
id?: number;
// The source of the translation
source?: string;
// The translated text
text?: string;
}
export interface Verse {
// The unique id of the verse in the whole book
id?: number;
// The interpretations of the verse
interpretations?: Interpretation[];
// The key of this verse (chapter:verse) e.g 1:1
key?: string;
// The verse number in this chapter
number?: number;
// The page of the Quran this verse is on
page?: number;
// The arabic text for this verse
text?: string;
// The basic translation of the verse
translatedText?: string;
// The alternative translations for the verse
translations?: Translation[];
// The phonetic transliteration from arabic
transliteration?: string;
// The individual words within the verse (Ayah)
words?: Word[];
}
export interface VersesRequest {
// The chapter id to retrieve
chapter?: number;
// Return the interpretation (tafsir)
interpret?: boolean;
// The language of translation
language?: string;
// The verses per page
limit?: number;
// The page number to request
page?: number;
// Return alternate translations
translate?: boolean;
// Return the individual words with the verses
words?: boolean;
}
export interface VersesResponse {
// The chapter requested
chapter?: number;
// The page requested
page?: number;
// The total pages
totalPages?: number;
// The verses on the page
verses?: Verse[];
}
export interface Word {
// The character type e.g word, end
charType?: string;
// The QCF v2 font code
code?: string;
// The id of the word within the verse
id?: number;
// The line number
line?: number;
// The page number
page?: number;
// The position of the word
position?: number;
// The arabic text for this word
text?: string;
// The translated text
translation?: string;
// The transliteration text
transliteration?: string;
}

View File

@@ -1,123 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class RoutingService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Turn by turn directions from a start point to an end point including maneuvers and bearings
directions(request: DirectionsRequest): Promise<DirectionsResponse> {
return this.client.call(
"routing",
"Directions",
request
) as Promise<DirectionsResponse>;
}
// Get the eta for a route from origin to destination. The eta is an estimated time based on car routes
eta(request: EtaRequest): Promise<EtaResponse> {
return this.client.call("routing", "Eta", request) as Promise<EtaResponse>;
}
// Retrieve a route as a simple list of gps points along with total distance and estimated duration
route(request: RouteRequest): Promise<RouteResponse> {
return this.client.call(
"routing",
"Route",
request
) as Promise<RouteResponse>;
}
}
export interface Direction {
// distance to travel in meters
distance?: number;
// duration to travel in seconds
duration?: number;
// human readable instruction
instruction?: string;
// intersections on route
intersections?: Intersection[];
// maneuver to take
maneuver?: { [key: string]: any };
// street name or location
name?: string;
// alternative reference
reference?: string;
}
export interface DirectionsRequest {
// The destination of the journey
destination?: Point;
// The staring point for the journey
origin?: Point;
}
export interface DirectionsResponse {
// Turn by turn directions
directions?: Direction[];
// Estimated distance of the route in meters
distance?: number;
// Estimated duration of the route in seconds
duration?: number;
// The waypoints on the route
waypoints?: Waypoint[];
}
export interface EtaRequest {
// The end point for the eta calculation
destination?: Point;
// The starting point for the eta calculation
origin?: Point;
// speed in kilometers
speed?: number;
// type of transport. Only "car" is supported currently.
type?: string;
}
export interface EtaResponse {
// eta in seconds
duration?: number;
}
export interface Intersection {
bearings?: number[];
location?: Point;
}
export interface Maneuver {
action?: string;
bearingAfter?: number;
bearingBefore?: number;
direction?: string;
location?: Point;
}
export interface Point {
// Lat e.g 52.523219
latitude?: number;
// Long e.g 13.428555
longitude?: number;
}
export interface RouteRequest {
// Point of destination for the trip
destination?: Point;
// Point of origin for the trip
origin?: Point;
}
export interface RouteResponse {
// estimated distance in meters
distance?: number;
// estimated duration in seconds
duration?: number;
// waypoints on the route
waypoints?: Waypoint[];
}
export interface Waypoint {
// gps point coordinates
location?: Point;
// street name or related reference
name?: string;
}

View File

@@ -1,99 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class RssService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Add a new RSS feed with a name, url, and category
add(request: AddRequest): Promise<AddResponse> {
return this.client.call("rss", "Add", request) as Promise<AddResponse>;
}
// Get an RSS feed by name. If no name is given, all feeds are returned. Default limit is 25 entries.
feed(request: FeedRequest): Promise<FeedResponse> {
return this.client.call("rss", "Feed", request) as Promise<FeedResponse>;
}
// List the saved RSS fields
list(request: ListRequest): Promise<ListResponse> {
return this.client.call("rss", "List", request) as Promise<ListResponse>;
}
// Remove an RSS feed by name
remove(request: RemoveRequest): Promise<RemoveResponse> {
return this.client.call(
"rss",
"Remove",
request
) as Promise<RemoveResponse>;
}
}
export interface AddRequest {
// category to add e.g news
category?: string;
// rss feed name
// eg. a16z
name?: string;
// rss feed url
// eg. http://a16z.com/feed/
url?: string;
}
export interface AddResponse {}
export interface Entry {
// article content
content?: string;
// data of the entry
date?: string;
// the rss feed where it came from
feed?: string;
// unique id of the entry
id?: string;
// rss feed url of the entry
link?: string;
// article summary
summary?: string;
// title of the entry
title?: string;
}
export interface Feed {
// category of the feed e.g news
category?: string;
// unique id
id?: string;
// rss feed name
// eg. a16z
name?: string;
// rss feed url
// eg. http://a16z.com/feed/
url?: string;
}
export interface FeedRequest {
// limit entries returned
limit?: number;
// rss feed name
name?: string;
// offset entries
offset?: number;
}
export interface FeedResponse {
entries?: Entry[];
}
export interface ListRequest {}
export interface ListResponse {
feeds?: Feed[];
}
export interface RemoveRequest {
// rss feed name
// eg. a16z
name?: string;
}
export interface RemoveResponse {}

View File

@@ -1,29 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class SentimentService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Analyze and score a piece of text
analyze(request: AnalyzeRequest): Promise<AnalyzeResponse> {
return this.client.call(
"sentiment",
"Analyze",
request
) as Promise<AnalyzeResponse>;
}
}
export interface AnalyzeRequest {
// The language. Defaults to english.
lang?: string;
// The text to analyze
text?: string;
}
export interface AnalyzeResponse {
// The score of the text {positive is 1, negative is 0}
score?: number;
}

View File

@@ -1,29 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class SmsService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Send an SMS.
send(request: SendRequest): Promise<SendResponse> {
return this.client.call("sms", "Send", request) as Promise<SendResponse>;
}
}
export interface SendRequest {
// who is the message from? The message will be suffixed with "Sent from <from>"
from?: string;
// the main body of the message to send
message?: string;
// the destination phone number including the international dialling code (e.g. +44)
to?: string;
}
export interface SendResponse {
// any additional info
info?: string;
// will return "ok" if successful
status?: string;
}

View File

@@ -1,132 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class StockService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Get the historic open-close for a given day
history(request: HistoryRequest): Promise<HistoryResponse> {
return this.client.call(
"stock",
"History",
request
) as Promise<HistoryResponse>;
}
// Get the historic order book and each trade by timestamp
orderBook(request: OrderBookRequest): Promise<OrderBookResponse> {
return this.client.call(
"stock",
"OrderBook",
request
) as Promise<OrderBookResponse>;
}
// Get the last price for a given stock ticker
price(request: PriceRequest): Promise<PriceResponse> {
return this.client.call(
"stock",
"Price",
request
) as Promise<PriceResponse>;
}
// Get the last quote for the stock
quote(request: QuoteRequest): Promise<QuoteResponse> {
return this.client.call(
"stock",
"Quote",
request
) as Promise<QuoteResponse>;
}
}
export interface HistoryRequest {
// date to retrieve as YYYY-MM-DD
date?: string;
// the stock symbol e.g AAPL
stock?: string;
}
export interface HistoryResponse {
// the close price
close?: number;
// the date
date?: string;
// the peak price
high?: number;
// the low price
low?: number;
// the open price
open?: number;
// the stock symbol
symbol?: string;
// the volume
volume?: number;
}
export interface Order {
// the asking price
askPrice?: number;
// the ask size
askSize?: number;
// the bidding price
bidPrice?: number;
// the bid size
bidSize?: number;
// the UTC timestamp of the quote
timestamp?: string;
}
export interface OrderBookRequest {
// the date in format YYYY-MM-dd
date?: string;
// optional RFC3339Nano end time e.g 2006-01-02T15:04:05.999999999Z07:00
end?: string;
// limit number of prices
limit?: number;
// optional RFC3339Nano start time e.g 2006-01-02T15:04:05.999999999Z07:00
start?: string;
// stock to retrieve e.g AAPL
stock?: string;
}
export interface OrderBookResponse {
// date of the request
date?: string;
// list of orders
orders?: Order[];
// the stock symbol
symbol?: string;
}
export interface PriceRequest {
// stock symbol e.g AAPL
symbol?: string;
}
export interface PriceResponse {
// the last price
price?: number;
// the stock symbol e.g AAPL
symbol?: string;
}
export interface QuoteRequest {
// the stock symbol e.g AAPL
symbol?: string;
}
export interface QuoteResponse {
// the asking price
askPrice?: number;
// the ask size
askSize?: number;
// the bidding price
bidPrice?: number;
// the bid size
bidSize?: number;
// the stock symbol
symbol?: string;
// the UTC timestamp of the quote
timestamp?: string;
}

View File

@@ -1,46 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class StreamService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Publish a message to the stream. Specify a topic to group messages for a specific topic.
publish(request: PublishRequest): Promise<PublishResponse> {
return this.client.call(
"stream",
"Publish",
request
) as Promise<PublishResponse>;
}
// Subscribe to messages for a given topic.
subscribe(request: SubscribeRequest): Promise<SubscribeResponse> {
return this.client.call(
"stream",
"Subscribe",
request
) as Promise<SubscribeResponse>;
}
}
export interface PublishRequest {
// The json message to publish
message?: { [key: string]: any };
// The topic to publish to
topic?: string;
}
export interface PublishResponse {}
export interface SubscribeRequest {
// The topic to subscribe to
topic?: string;
}
export interface SubscribeResponse {
// The next json message on the topic
message?: { [key: string]: any };
// The topic subscribed to
topic?: string;
}

View File

@@ -1,183 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class SunnahService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Get a list of books from within a collection. A book can contain many chapters
// each with its own hadiths.
books(request: BooksRequest): Promise<BooksResponse> {
return this.client.call(
"sunnah",
"Books",
request
) as Promise<BooksResponse>;
}
// Get all the chapters of a given book within a collection.
chapters(request: ChaptersRequest): Promise<ChaptersResponse> {
return this.client.call(
"sunnah",
"Chapters",
request
) as Promise<ChaptersResponse>;
}
// Get a list of available collections. A collection is
// a compilation of hadiths collected and written by an author.
collections(request: CollectionsRequest): Promise<CollectionsResponse> {
return this.client.call(
"sunnah",
"Collections",
request
) as Promise<CollectionsResponse>;
}
// Hadiths returns a list of hadiths and their corresponding text for a
// given book within a collection.
hadiths(request: HadithsRequest): Promise<HadithsResponse> {
return this.client.call(
"sunnah",
"Hadiths",
request
) as Promise<HadithsResponse>;
}
}
export interface Book {
// arabic name of the book
arabicName?: string;
// number of hadiths in the book
hadiths?: number;
// number of the book e.g 1
id?: number;
// name of the book
name?: string;
}
export interface BooksRequest {
// Name of the collection
collection?: string;
// Limit the number of books returned
limit?: number;
// The page in the pagination
page?: number;
}
export interface BooksResponse {
// A list of books
books?: Book[];
// Name of the collection
collection?: string;
// The limit specified
limit?: number;
// The page requested
page?: number;
// The total overall books
total?: number;
}
export interface Chapter {
// arabic title
arabicTitle?: string;
// the book number
book?: number;
// the chapter id e.g 1
id?: number;
// the chapter key e.g 1.00
key?: string;
// title of the chapter
title?: string;
}
export interface ChaptersRequest {
// number of the book
book?: number;
// name of the collection
collection?: string;
// Limit the number of chapters returned
limit?: number;
// The page in the pagination
page?: number;
}
export interface ChaptersResponse {
// number of the book
book?: number;
// The chapters of the book
chapters?: Chapter[];
// name of the collection
collection?: string;
// Limit the number of chapters returned
limit?: number;
// The page in the pagination
page?: number;
// Total chapters in the book
total?: number;
}
export interface Collection {
// Arabic title if available
arabicTitle?: string;
// Total hadiths in the collection
hadiths?: number;
// Name of the collection e.g bukhari
name?: string;
// An introduction explaining the collection
summary?: string;
// Title of the collection e.g Sahih al-Bukhari
title?: string;
}
export interface CollectionsRequest {
// Number of collections to limit to
limit?: number;
// The page in the pagination
page?: number;
}
export interface CollectionsResponse {
collections?: Collection[];
}
export interface Hadith {
// the arabic chapter title
arabicChapterTitle?: string;
// the arabic text
arabicText?: string;
// the chapter id
chapter?: number;
// the chapter key
chapterKey?: string;
// the chapter title
chapterTitle?: string;
// hadith id
id?: number;
// hadith text
text?: string;
}
export interface HadithsRequest {
// number of the book
book?: number;
// name of the collection
collection?: string;
// Limit the number of hadiths
limit?: number;
// The page in the pagination
page?: number;
}
export interface HadithsResponse {
// number of the book
book?: number;
// name of the collection
collection?: string;
// The hadiths of the book
hadiths?: Hadith[];
// Limit the number of hadiths returned
limit?: number;
// The page in the pagination
page?: number;
// Total hadiths in the book
total?: number;
}

View File

@@ -1,29 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class ThumbnailService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Create a thumbnail screenshot by passing in a url, height and width
screenshot(request: ScreenshotRequest): Promise<ScreenshotResponse> {
return this.client.call(
"thumbnail",
"Screenshot",
request
) as Promise<ScreenshotResponse>;
}
}
export interface ScreenshotRequest {
// height of the browser window, optional
height?: number;
url?: string;
// width of the browser window. optional
width?: number;
}
export interface ScreenshotResponse {
imageURL?: string;
}

View File

@@ -1,61 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class TimeService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Get the current time
now(request: NowRequest): Promise<NowResponse> {
return this.client.call("time", "Now", request) as Promise<NowResponse>;
}
// Get the timezone info for a specific location
zone(request: ZoneRequest): Promise<ZoneResponse> {
return this.client.call("time", "Zone", request) as Promise<ZoneResponse>;
}
}
export interface NowRequest {
// optional location, otherwise returns UTC
location?: string;
}
export interface NowResponse {
// the current time as HH:MM:SS
localtime?: string;
// the location as Europe/London
location?: string;
// timestamp as 2006-01-02T15:04:05.999999999Z07:00
timestamp?: string;
// the timezone as BST
timezone?: string;
// the unix timestamp
unix?: number;
}
export interface ZoneRequest {
// location to lookup e.g postcode, city, ip address
location?: string;
}
export interface ZoneResponse {
// the abbreviated code e.g BST
abbreviation?: string;
// country of the timezone
country?: string;
// is daylight savings
dst?: boolean;
// e.g 51.42
latitude?: number;
// the local time
localtime?: string;
// location requested
location?: string;
// e.g -0.37
longitude?: number;
// region of timezone
region?: string;
// the timezone e.g Europe/London
timezone?: string;
}

View File

@@ -1,16 +0,0 @@
{
"compilerOptions": {
"module": "ES2015",
"target": "ES6",
"declaration": true,
"lib": ["es2015", "dom"],
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"outDir": "./tmp/esm",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true
},
"include": ["src/index.ts", "src/**/*"],
"exclude": ["./dist", "./node_modules"]
}

View File

@@ -1,16 +0,0 @@
{
"compilerOptions": {
"module": "CommonJS",
"target": "es5",
"declaration": true,
"lib": ["es2015", "dom"],
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"outDir": "./tmp",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true
},
"include": ["src/index.ts", "src/**/*"],
"exclude": ["./dist", "./node_modules"]
}

View File

@@ -1,131 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class TwitterService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Search for tweets with a simple query
search(request: SearchRequest): Promise<SearchResponse> {
return this.client.call(
"twitter",
"Search",
request
) as Promise<SearchResponse>;
}
// Get the timeline for a given user
timeline(request: TimelineRequest): Promise<TimelineResponse> {
return this.client.call(
"twitter",
"Timeline",
request
) as Promise<TimelineResponse>;
}
// Get the current global trending topics
trends(request: TrendsRequest): Promise<TrendsResponse> {
return this.client.call(
"twitter",
"Trends",
request
) as Promise<TrendsResponse>;
}
// Get a user's twitter profile
user(request: UserRequest): Promise<UserResponse> {
return this.client.call(
"twitter",
"User",
request
) as Promise<UserResponse>;
}
}
export interface Profile {
// the account creation date
createdAt?: string;
// the user description
description?: string;
// the follower count
followers?: number;
// the user id
id?: number;
// The user's profile picture
imageUrl?: string;
// the user's location
location?: string;
// display name of the user
name?: string;
// if the account is private
private?: boolean;
// the username
username?: string;
// if the account is verified
verified?: boolean;
}
export interface SearchRequest {
// number of tweets to return. default: 20
limit?: number;
// the query to search for
query?: string;
}
export interface SearchResponse {
// the related tweets for the search
tweets?: Tweet[];
}
export interface TimelineRequest {
// number of tweets to return. default: 20
limit?: number;
// the username to request the timeline for
username?: string;
}
export interface TimelineResponse {
// The recent tweets for the user
tweets?: Tweet[];
}
export interface Trend {
// name of the trend
name?: string;
// the volume of tweets in last 24 hours
tweetVolume?: number;
// the twitter url
url?: string;
}
export interface TrendsRequest {}
export interface TrendsResponse {
// a list of trending topics
trends?: Trend[];
}
export interface Tweet {
// time of tweet
createdAt?: string;
// number of times favourited
favouritedCount?: number;
// id of the tweet
id?: number;
// number of times retweeted
retweetedCount?: number;
// text of the tweet
text?: string;
// username of the person who tweeted
username?: string;
}
export interface UserRequest {
// the username to lookup
username?: string;
}
export interface UserResponse {
// The requested user profile
profile?: { [key: string]: any };
// the current user status
status?: Tweet;
}

View File

@@ -1,63 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class UrlService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// List information on all the shortened URLs that you have created
list(request: ListRequest): Promise<ListResponse> {
return this.client.call("url", "List", request) as Promise<ListResponse>;
}
// Proxy returns the destination URL of a short URL.
proxy(request: ProxyRequest): Promise<ProxyResponse> {
return this.client.call("url", "Proxy", request) as Promise<ProxyResponse>;
}
// Shortens a destination URL and returns a full short URL.
shorten(request: ShortenRequest): Promise<ShortenResponse> {
return this.client.call(
"url",
"Shorten",
request
) as Promise<ShortenResponse>;
}
}
export interface ListRequest {
// filter by short URL, optional
shortURL?: string;
}
export interface ListResponse {
urlPairs?: URLPair;
}
export interface ProxyRequest {
// short url ID, without the domain, eg. if your short URL is
// `m3o.one/u/someshorturlid` then pass in `someshorturlid`
shortURL?: string;
}
export interface ProxyResponse {
destinationURL?: string;
}
export interface ShortenRequest {
destinationURL?: string;
}
export interface ShortenResponse {
shortURL?: string;
}
export interface URLPair {
created?: number;
destinationURL?: string;
// HitCount keeps track many times the short URL has been resolved.
// Hitcount only gets saved to disk (database) after every 10th hit, so
// its not intended to be 100% accurate, more like an almost correct estimate.
hitCount?: number;
owner?: string;
shortURL?: string;
}

View File

@@ -1,233 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class UserService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Create a new user account. The email address and username for the account must be unique.
create(request: CreateRequest): Promise<CreateResponse> {
return this.client.call(
"user",
"Create",
request
) as Promise<CreateResponse>;
}
// Delete an account by id
delete(request: DeleteRequest): Promise<DeleteResponse> {
return this.client.call(
"user",
"Delete",
request
) as Promise<DeleteResponse>;
}
// Login using username or email. The response will return a new session for successful login,
// 401 in the case of login failure and 500 for any other error
login(request: LoginRequest): Promise<LoginResponse> {
return this.client.call("user", "Login", request) as Promise<LoginResponse>;
}
// Logout a user account
logout(request: LogoutRequest): Promise<LogoutResponse> {
return this.client.call(
"user",
"Logout",
request
) as Promise<LogoutResponse>;
}
// Read an account by id, username or email. Only one need to be specified.
read(request: ReadRequest): Promise<ReadResponse> {
return this.client.call("user", "Read", request) as Promise<ReadResponse>;
}
// Read a session by the session id. In the event it has expired or is not found and error is returned.
readSession(request: ReadSessionRequest): Promise<ReadSessionResponse> {
return this.client.call(
"user",
"ReadSession",
request
) as Promise<ReadSessionResponse>;
}
// Send a verification email
// to the user being signed up. Email from will be from 'support@m3o.com',
// but you can provide the title and contents.
// The verification link will be injected in to the email as a template variable, $micro_verification_link.
// Example: 'Hi there, welcome onboard! Use the link below to verify your email: $micro_verification_link'
// The variable will be replaced with an actual url that will look similar to this:
// 'https://user.m3o.com/user/verify?token=a-verification-token&redirectUrl=your-redir-url'
sendVerificationEmail(
request: SendVerificationEmailRequest
): Promise<SendVerificationEmailResponse> {
return this.client.call(
"user",
"SendVerificationEmail",
request
) as Promise<SendVerificationEmailResponse>;
}
// Update the account password
updatePassword(
request: UpdatePasswordRequest
): Promise<UpdatePasswordResponse> {
return this.client.call(
"user",
"UpdatePassword",
request
) as Promise<UpdatePasswordResponse>;
}
// Update the account username or email
update(request: UpdateRequest): Promise<UpdateResponse> {
return this.client.call(
"user",
"Update",
request
) as Promise<UpdateResponse>;
}
// Verify the email address of an account from a token sent in an email to the user.
verifyEmail(request: VerifyEmailRequest): Promise<VerifyEmailResponse> {
return this.client.call(
"user",
"VerifyEmail",
request
) as Promise<VerifyEmailResponse>;
}
}
export interface Account {
// unix timestamp
created?: number;
// an email address
email?: string;
// unique account id
id?: string;
// Store any custom data you want about your users in this fields.
profile?: { [key: string]: string };
// unix timestamp
updated?: number;
// alphanumeric username
username?: string;
verificationDate?: number;
verified?: boolean;
}
export interface CreateRequest {
// the email address
email?: string;
// optional account id
id?: string;
// the user password
password?: string;
// optional user profile as map<string,string>
profile?: { [key: string]: string };
// the username
username?: string;
}
export interface CreateResponse {
account?: { [key: string]: any };
}
export interface DeleteRequest {
// the account id
id?: string;
}
export interface DeleteResponse {}
export interface LoginRequest {
// The email address of the user
email?: string;
// The password of the user
password?: string;
// The username of the user
username?: string;
}
export interface LoginResponse {
// The session of the logged in user
session?: { [key: string]: any };
}
export interface LogoutRequest {
sessionId?: string;
}
export interface LogoutResponse {}
export interface ReadRequest {
// the account email
email?: string;
// the account id
id?: string;
// the account username
username?: string;
}
export interface ReadResponse {
account?: { [key: string]: any };
}
export interface ReadSessionRequest {
// The unique session id
sessionId?: string;
}
export interface ReadSessionResponse {
session?: { [key: string]: any };
}
export interface SendVerificationEmailRequest {
email?: string;
failureRedirectUrl?: string;
// Display name of the sender for the email. Note: the email address will still be 'support@m3o.com'
fromName?: string;
redirectUrl?: string;
subject?: string;
// Text content of the email. Don't forget to include the string '$micro_verification_link' which will be replaced by the real verification link
// HTML emails are not available currently.
textContent?: string;
}
export interface SendVerificationEmailResponse {}
export interface Session {
// unix timestamp
created?: number;
// unix timestamp
expires?: number;
// the session id
id?: string;
// the associated user id
userId?: string;
}
export interface UpdatePasswordRequest {
// confirm new password
confirmPassword?: string;
// the new password
newPassword?: string;
// the old password
oldPassword?: string;
// the account id
userId?: string;
}
export interface UpdatePasswordResponse {}
export interface UpdateRequest {
// the new email address
email?: string;
// the account id
id?: string;
// the user profile as map<string,string>
profile?: { [key: string]: string };
// the new username
username?: string;
}
export interface UpdateResponse {}
export interface VerifyEmailRequest {
// The token from the verification email
token?: string;
}
export interface VerifyEmailResponse {}

View File

@@ -1,55 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class VehicleService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Lookup a UK vehicle by it's registration number
lookup(request: LookupRequest): Promise<LookupResponse> {
return this.client.call(
"vehicle",
"Lookup",
request
) as Promise<LookupResponse>;
}
}
export interface LookupRequest {
// the vehicle registration number
registration?: string;
}
export interface LookupResponse {
// co2 emmissions
co2Emissions?: number;
// colour of vehicle
colour?: string;
// engine capacity
engineCapacity?: number;
// fuel type e.g petrol, diesel
fuelType?: string;
// date of last v5 issue
lastV5Issued?: string;
// make of vehicle
make?: string;
// month of first registration
monthOfFirstRegistration?: string;
// mot expiry
motExpiry?: string;
// mot status
motStatus?: string;
// registration number
registration?: string;
// tax due data
taxDueDate?: string;
// tax status
taxStatus?: string;
// type approvale
typeApproval?: string;
// wheel plan
wheelplan?: string;
// year of manufacture
yearOfManufacture?: number;
}

View File

@@ -1,124 +0,0 @@
import * as m3o from "@m3o/m3o-node";
export class WeatherService {
private client: m3o.Client;
constructor(token: string) {
this.client = new m3o.Client({ token: token });
}
// Get the weather forecast for the next 1-10 days
forecast(request: ForecastRequest): Promise<ForecastResponse> {
return this.client.call(
"weather",
"Forecast",
request
) as Promise<ForecastResponse>;
}
// Get the current weather report for a location by postcode, city, zip code, ip address
now(request: NowRequest): Promise<NowResponse> {
return this.client.call("weather", "Now", request) as Promise<NowResponse>;
}
}
export interface Forecast {
// the average temp in celsius
avgTempC?: number;
// the average temp in fahrenheit
avgTempF?: number;
// chance of rain (percentage)
chanceOfRain?: number;
// forecast condition
condition?: string;
// date of the forecast
date?: string;
// the URL of forecast condition icon. Simply prefix with either http or https to use it
iconUrl?: string;
// max temp in celsius
maxTempC?: number;
// max temp in fahrenheit
maxTempF?: number;
// minimum temp in celsius
minTempC?: number;
// minimum temp in fahrenheit
minTempF?: number;
// time of sunrise
sunrise?: string;
// time of sunset
sunset?: string;
// will it rain
willItRain?: boolean;
}
export interface ForecastRequest {
// number of days. default 1, max 10
days?: number;
// location of the forecase
location?: string;
}
export interface ForecastResponse {
// country of the request
country?: string;
// forecast for the next number of days
forecast?: { [key: string]: any }[];
// e.g 37.55
latitude?: number;
// the local time
localTime?: string;
// location of the request
location?: string;
// e.g -77.46
longitude?: number;
// region related to the location
region?: string;
// timezone of the location
timezone?: string;
}
export interface NowRequest {
// location to get weather e.g postcode, city
location?: string;
}
export interface NowResponse {
// cloud cover percentage
cloud?: number;
// the weather condition
condition?: string;
// country of the request
country?: string;
// whether its daytime
daytime?: boolean;
// feels like in celsius
feelsLikeC?: number;
// feels like in fahrenheit
feelsLikeF?: number;
// the humidity percentage
humidity?: number;
// the URL of the related icon. Simply prefix with either http or https to use it
iconUrl?: string;
// e.g 37.55
latitude?: number;
// the local time
localTime?: string;
// location of the request
location?: string;
// e.g -77.46
longitude?: number;
// region related to the location
region?: string;
// temperature in celsius
tempC?: number;
// temperature in fahrenheit
tempF?: number;
// timezone of the location
timezone?: string;
// wind degree
windDegree?: number;
// wind direction
windDirection?: string;
// wind in kph
windKph?: number;
// wind in mph
windMph?: number;
}

View File

@@ -1,17 +0,0 @@
# Client and example generation
To run the code generation, from the repo root issue:
```sh
go install ./cmd/clients; clients .
```
The generated clients will end up in `./clients`.
Take inspiration from the `.github/workflows/publish.yml` to see how to publish the NPM package.
# Typescript gotchas
There is some funkiness going on with the package names in the generator -

View File

@@ -1,198 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"sort"
"strings"
"github.com/crufter/nested"
"github.com/getkin/kin-openapi/openapi3"
"github.com/stoewer/go-strcase"
)
func schemaToGoExample(serviceName, typeName string, schemas map[string]*openapi3.SchemaRef, values map[string]interface{}) string {
var recurse func(props map[string]*openapi3.SchemaRef, path []string) string
var spec *openapi3.SchemaRef = schemas[typeName]
if spec == nil {
existing := ""
for k, _ := range schemas {
existing += k + " "
}
panic("can't find schema " + typeName + " but found " + existing)
}
detectType := func(currentType string, properties map[string]*openapi3.SchemaRef) (string, bool) {
index := map[string]bool{}
for key, prop := range properties {
index[key+prop.Value.Title] = true
}
for k, schema := range schemas {
// we don't want to return the type matching itself
if strings.ToLower(k) == currentType {
continue
}
if strings.HasSuffix(k, "Request") || strings.HasSuffix(k, "Response") {
continue
}
if len(schema.Value.Properties) != len(properties) {
continue
}
found := false
for key, prop := range schema.Value.Properties {
_, ok := index[key+prop.Value.Title]
found = ok
if !ok {
break
}
}
if found {
return schema.Value.Title, true
}
}
return "", false
}
var fieldSeparator, objectOpen, objectClose, arrayPrefix, arrayPostfix, fieldDelimiter, stringType, boolType string
var int32Type, int64Type, floatType, doubleType, mapType, anyType, typeInstancePrefix string
var fieldUpperCase bool
language := "go"
switch language {
case "go":
fieldUpperCase = true
fieldSeparator = ": "
arrayPrefix = "[]"
arrayPostfix = ""
objectOpen = "{\n"
objectClose = "}"
fieldDelimiter = ","
stringType = "string"
boolType = "bool"
int32Type = "int32"
int64Type = "int64"
floatType = "float32"
doubleType = "float64"
mapType = "map[string]%v"
anyType = "interface{}"
typeInstancePrefix = "&"
}
valueToType := func(v *openapi3.SchemaRef) string {
switch v.Value.Type {
case "string":
return stringType
case "boolean":
return boolType
case "number":
switch v.Value.Format {
case "int32":
return int32Type
case "int64":
return int64Type
case "float":
return floatType
case "double":
return doubleType
}
default:
return "unrecognized: " + v.Value.Type
}
return ""
}
printMap := func(m map[string]interface{}, level int) string {
ret := ""
for k, v := range m {
marsh, _ := json.Marshal(v)
ret += strings.Repeat("\t", level) + fmt.Sprintf("\"%v\": %v,\n", k, string(marsh))
}
return ret
}
recurse = func(props map[string]*openapi3.SchemaRef, path []string) string {
ret := ""
i := 0
var keys []string
for k := range props {
keys = append(keys, k)
}
sort.Strings(keys)
for i, v := range path {
path[i] = strcase.LowerCamelCase(v)
}
for _, k := range keys {
v := props[k]
ret += strings.Repeat("\t", len(path))
if fieldUpperCase {
k = strcase.UpperCamelCase(k)
}
var val interface{}
p := strings.Replace(strings.Join(append(path, strcase.LowerCamelCase(k)), "."), ".[", "[", -1)
val, ok := nested.Get(values, p)
if !ok {
continue
}
// hack
if str, ok := val.(string); ok {
if str == "<nil>" {
continue
}
}
switch v.Value.Type {
case "object":
typ, found := detectType(k, v.Value.Properties)
if found {
ret += k + fieldSeparator + typeInstancePrefix + serviceName + "." + strings.Title(typ) + objectOpen + recurse(v.Value.Properties, append(path, k)) + objectClose + fieldDelimiter
} else {
// type is a dynamic map
// if additional properties is present, then it's a map string string or other typed map
if v.Value.AdditionalProperties != nil {
ret += k + fieldSeparator + fmt.Sprintf(mapType, valueToType(v.Value.AdditionalProperties)) + objectOpen + printMap(val.(map[string]interface{}), len(path)+1) + objectClose + fieldDelimiter
} else {
// if additional properties is not present, it's an any type,
// like the proto struct type
ret += k + fieldSeparator + fmt.Sprintf(mapType, anyType) + objectOpen + printMap(val.(map[string]interface{}), len(path)+1) + objectClose + fieldDelimiter
}
}
case "array":
typ, found := detectType(k, v.Value.Items.Value.Properties)
if found {
ret += k + fieldSeparator + arrayPrefix + serviceName + "." + strings.Title(typ) + objectOpen + serviceName + "." + strings.Title(typ) + objectOpen + recurse(v.Value.Items.Value.Properties, append(append(path, k), "[0]")) + objectClose + objectClose + arrayPostfix + fieldDelimiter
} else {
arrint := val.([]interface{})
switch v.Value.Items.Value.Type {
case "string":
arrstr := make([]string, len(arrint))
for i, v := range arrint {
arrstr[i] = fmt.Sprintf("%v", v)
}
ret += k + fieldSeparator + fmt.Sprintf("%#v", arrstr) + fieldDelimiter
case "number", "boolean":
ret += k + fieldSeparator + arrayPrefix + fmt.Sprintf("%v", val) + arrayPostfix + fieldDelimiter
case "object":
ret += k + fieldSeparator + arrayPrefix + fmt.Sprintf(mapType, valueToType(v.Value.AdditionalProperties)) + objectOpen + fmt.Sprintf(mapType, valueToType(v.Value.AdditionalProperties)) + objectOpen + recurse(v.Value.Items.Value.Properties, append(append(path, k), "[0]")) + strings.Repeat("\t", len(path)) + objectClose + objectClose + arrayPostfix + fieldDelimiter
}
}
case "string":
if strings.Contains(val.(string), "\n") {
ret += k + fieldSeparator + fmt.Sprintf("`%v`", val) + fieldDelimiter
} else {
ret += k + fieldSeparator + fmt.Sprintf("\"%v\"", val) + fieldDelimiter
}
case "number", "boolean":
ret += k + fieldSeparator + fmt.Sprintf("%v", val) + fieldDelimiter
}
if i < len(props) {
ret += "\n"
}
i++
}
return ret
}
return recurse(spec.Value.Properties, []string{})
}

View File

@@ -1,485 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/Masterminds/semver/v3"
"github.com/getkin/kin-openapi/openapi3"
)
func TestSemver(t *testing.T) {
v, _ := semver.NewVersion("0.0.0-beta1")
if incBeta(*v).String() != "0.0.0-beta2" {
t.Fatal(v)
}
v1, _ := semver.NewVersion("0.0.1")
if !v1.GreaterThan(v) {
t.Fatal("no good")
}
v2, _ := semver.NewVersion("0.0.0")
if !v2.GreaterThan(v) {
t.Fatal("no good")
}
if v.String() != "0.0.0-beta1" {
t.Fatal("no good")
}
v3, _ := semver.NewVersion("0.0.0-beta2")
if !v3.GreaterThan(v) {
t.Fatal("no good")
}
}
type tspec struct {
openapi string
tsresult string
key string
}
var cases = []tspec{
{
openapi: `{
"components": {
"schemas": {
"QueryRequest": {
"description": "Query posts. Acts as a listing when no id or slug provided.\n Gets a single post by id or slug if any of them provided.",
"properties": {
"id": {
"type": "string"
},
"limit": {
"format": "int64",
"type": "number"
},
"offset": {
"format": "int64",
"type": "number"
},
"slug": {
"type": "string"
},
"tag": {
"type": "string"
}
},
"title": "QueryRequest",
"type": "object"
}
}
}
}`,
key: "QueryRequest",
tsresult: `export interface QueryRequest {
id?: string;
limit?: number;
offset?: number;
slug?: string;
tag?: string;
}`,
},
{
openapi: `{"components": { "schemas": {
"QueryResponse": {
"properties": {
"posts": {
"items": {
"properties": {
"author": {
"type": "string"
},
"content": {
"type": "string"
},
"created": {
"format": "int64",
"type": "number"
},
"id": {
"type": "string"
},
"image": {
"type": "string"
},
"metadata": {
"items": {
"properties": {
"key": {
"type": "string"
},
"value": {
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"slug": {
"type": "string"
},
"tags": {
"items": {
"type": "string"
},
"type": "array"
},
"title": {
"type": "string"
},
"updated": {
"format": "int64",
"type": "number"
}
},
"type": "object"
},
"type": "array"
}
},
"title": "QueryResponse",
"type": "object"
}}}}`,
key: "QueryResponse",
tsresult: `
export interface QueryResponse {
posts?: {
author?: string;
content?: string;
created?: number;
id?: string;
image?: string;
metadata?: {
key?: string;
value?: string;
}[];
slug?: string;
tags?: string[];
title?: string;
updated?: number;
}[];
}`,
},
}
func TestTsGen(t *testing.T) {
// @todo fix tests to be up to date
return
for _, c := range cases {
spec := &openapi3.Swagger{}
err := json.Unmarshal([]byte(c.openapi), &spec)
if err != nil {
t.Fatal(err)
}
//spew.Dump(spec.Components.Schemas)
res := schemaToType("typescript", "ServiceName", c.key, spec.Components.Schemas)
if res != c.tsresult {
t.Logf("Expected %v, got: %v", c.tsresult, res)
}
}
}
func TestTimeExample(t *testing.T) {
spec := &openapi3.Swagger{}
err := json.Unmarshal([]byte(timeExample), &spec)
if err != nil {
t.Fatal(err)
}
if len(spec.Components.Schemas) == 0 {
t.Fatal("boo")
}
fmt.Println(spec.Components.Schemas)
res := schemaToGoExample("time", "NowRequest", spec.Components.Schemas, map[string]interface{}{
"location": "London",
})
if strings.TrimSpace(res) != strings.TrimSpace(timeExp) {
t.Log(res, timeExp)
}
fmt.Println(spec.Components.Schemas)
res = schemaToGoExample("time", "ZoneRequest", spec.Components.Schemas, map[string]interface{}{
"location": "London",
})
if strings.TrimSpace(res) != strings.TrimSpace(timeExp) {
t.Log(res, timeExp)
}
}
const timeExample = `{
"components": {
"schemas": {
"NowRequest": {
"description": "Get the current time",
"properties": {
"location": {
"description": "optional location, otherwise returns UTC",
"type": "string"
}
},
"title": "NowRequest",
"type": "object"
},
"NowResponse": {
"properties": {
"localtime": {
"description": "the current time as HH:MM:SS",
"type": "string"
},
"location": {
"description": "the location as Europe/London",
"type": "string"
},
"timestamp": {
"description": "timestamp as 2006-01-02T15:04:05.999999999Z07:00",
"type": "string"
},
"timezone": {
"description": "the timezone as BST",
"type": "string"
},
"unix": {
"description": "the unix timestamp",
"format": "int64",
"type": "number"
}
},
"title": "NowResponse",
"type": "object"
},
"ZoneRequest": {
"description": "Get the timezone info for a specific location",
"properties": {
"location": {
"description": "location to lookup e.g postcode, city, ip address",
"type": "string"
}
},
"title": "ZoneRequest",
"type": "object"
},
"ZoneResponse": {
"properties": {
"abbreviation": {
"description": "the abbreviated code e.g BST",
"type": "string"
},
"country": {
"description": "country of the timezone",
"type": "string"
},
"dst": {
"description": "is daylight savings",
"type": "boolean"
},
"latitude": {
"description": "e.g 51.42",
"format": "double",
"type": "number"
},
"localtime": {
"description": "the local time",
"type": "string"
},
"location": {
"description": "location requested",
"type": "string"
},
"longitude": {
"description": "e.g -0.37",
"format": "double",
"type": "number"
},
"region": {
"description": "region of timezone",
"type": "string"
},
"timezone": {
"description": "the timezone e.g Europe/London",
"type": "string"
}
},
"title": "ZoneResponse",
"type": "object"
}
}
}
}`
const timeExp = `Location: London,
`
func TestExample(t *testing.T) {
spec := &openapi3.Swagger{}
err := json.Unmarshal([]byte(arrayExample), &spec)
if err != nil {
t.Fatal(err)
}
if len(spec.Components.Schemas) == 0 {
t.Fatal("boo")
}
//spew.Dump(spec.Components.Schemas)
res := schemaToGoExample("file", "ListResponse", spec.Components.Schemas, map[string]interface{}{
"files": []map[string]interface{}{
{
"content": "something something",
"created": "2021-05-20T13:37:21Z",
"path": "/documents/text-files/file.txt",
"metadata": map[string]interface{}{
"meta1": "value1",
"meta2": "value2",
},
"project": "my-project",
"updated": "2021-05-20T14:37:21Z",
},
},
})
if strings.TrimSpace(res) != strings.TrimSpace(arrayExp) {
t.Log(res, arrayExp)
}
spec = &openapi3.Swagger{}
err = json.Unmarshal([]byte(simpleExample), &spec)
if err != nil {
t.Log(err)
}
if len(spec.Components.Schemas) == 0 {
t.Log("boo")
}
fmt.Println(spec.Components.Schemas)
res = schemaToGoExample("file", "DeleteRequest", spec.Components.Schemas, map[string]interface{}{
"project": "examples",
"path": "/document/text-files/file.txt",
})
if strings.TrimSpace(res) != strings.TrimSpace(simpleExp) {
t.Log(res, arrayExp)
}
}
const simpleExample = `{
"components": {
"schemas": {
"DeleteRequest": {
"description": "Delete a file by project name/path",
"properties": {
"path": {
"description": "Path to the file",
"type": "string"
},
"project": {
"description": "The project name",
"type": "string"
}
},
"title": "DeleteRequest",
"type": "object"
}
}
}
}`
const simpleExp = `Path: "/document/text-files/file.txt"
Project: "exaples"
`
const arrayExp = `Files: []file.Record{
file.Record{
Content: "something something",
Created: "2021-05-20T13:37:21Z",
Metadata: map[string]string{
"meta1": "value1",
"meta2": "value2",
},
Path: "/documents/text-files/file.txt",
Project: "my-project",
Updated: "2021-05-20T14:37:21Z",
}},`
const arrayExample = `{
"components": {
"schemas": {
"ListResponse": {
"properties": {
"files": {
"items": {
"properties": {
"content": {
"description": "File contents",
"type": "string"
},
"created": {
"description": "Time the file was created e.g 2021-05-20T13:37:21Z",
"type": "string"
},
"metadata": {
"additionalProperties": {
"type": "string"
},
"description": "Any other associated metadata as a map of key-value pairs",
"type": "object"
},
"path": {
"description": "Path to file or folder eg. '/documents/text-files/file.txt'.",
"type": "string"
},
"project": {
"description": "A custom project to group files\n eg. file-of-mywebsite.com",
"type": "string"
},
"updated": {
"description": "Time the file was updated e.g 2021-05-20T13:37:21Z",
"type": "string"
}
},
"type": "object"
},
"type": "array"
}
},
"title": "ListResponse",
"type": "object"
},
"Record": {
"properties": {
"content": {
"description": "File contents",
"type": "string"
},
"created": {
"description": "Time the file was created e.g 2021-05-20T13:37:21Z",
"type": "string"
},
"metadata": {
"additionalProperties": {
"type": "string"
},
"description": "Any other associated metadata as a map of key-value pairs",
"type": "object"
},
"path": {
"description": "Path to file or folder eg. '/documents/text-files/file.txt'.",
"type": "string"
},
"project": {
"description": "A custom project to group files\n eg. file-of-mywebsite.com",
"type": "string"
},
"updated": {
"description": "Time the file was updated e.g 2021-05-20T13:37:21Z",
"type": "string"
}
},
"title": "Record",
"type": "object"
}
}
}
}`

View File

@@ -1,78 +0,0 @@
package main
const goIndexTemplate = `package services
import(
{{ range $service := .services }}"github.com/micro/services/clients/go/{{ $service.Name}}"
{{ end }}
)
func NewClient(token string) *Client {
return &Client{
token: token,
{{ range $service := .services }}
{{ title $service.Name }}Service: {{ $service.Name }}.New{{ title $service.Name}}Service(token),{{end}}
}
}
type Client struct {
token string
{{ range $service := .services }}
{{ title $service.Name }}Service *{{ $service.Name }}.{{ title $service.Name }}Service{{end}}
}
`
const goServiceTemplate = `{{ $service := .service }}package {{ $service.Name }}
import(
"github.com/micro/micro-go/client"
)
func New{{ title $service.Name }}Service(token string) *{{ title $service.Name }}Service {
return &{{ title $service.Name }}Service{
client: client.NewClient(&client.Options{
Token: token,
}),
}
}
type {{ title $service.Name }}Service struct {
client *client.Client
}
{{ range $key, $req := $service.Spec.Components.RequestBodies }}
{{ $endpointName := requestTypeToEndpointName $key}}{{ if endpointComment $endpointName $service.Spec.Components.Schemas }}{{ endpointComment $endpointName $service.Spec.Components.Schemas }}{{ end }}func (t *{{ title $service.Name }}Service) {{ $endpointName }}(request *{{ requestType $key }}) (*{{ requestTypeToResponseType $key }}, error) {
rsp := &{{ requestTypeToResponseType $key }}{}
return rsp, t.client.Call("{{ $service.Name }}", "{{ requestTypeToEndpointPath $key}}", request, rsp)
}
{{ end }}
{{ range $typeName, $schema := $service.Spec.Components.Schemas }}
type {{ title $typeName }} struct {{ "{" }}
{{ recursiveTypeDefinition "go" $service.Name $typeName $service.Spec.Components.Schemas }}{{ "}" }}
{{end}}
`
const goExampleTemplate = `{{ $service := .service }}package example
import(
"fmt"
"os"
"github.com/micro/services/clients/go/{{ $service.Name}}"
)
{{ if endpointComment .endpoint $service.Spec.Components.Schemas }}{{ endpointComment .endpoint $service.Spec.Components.Schemas }}{{ end }}func {{ .funcName }}() {
{{ $service.Name }}Service := {{ $service.Name }}.New{{ title $service.Name }}Service(os.Getenv("MICRO_API_TOKEN"))
rsp, err := {{ $service.Name }}Service.{{ title .endpoint }}(&{{ $service.Name }}.{{ title .endpoint }}Request{
{{ goExampleRequest $service.Name .endpoint $service.Spec.Components.Schemas .example.Request }}
})
fmt.Println(rsp, err)
}
`
const curlExampleTemplate = `{{ $service := .service }}curl "http://localhost:8080/{{ $service.Name }}/{{ title .endpoint }}" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $MICRO_API_TOKEN" \
-d '{{ tsExampleRequest $service.Name .endpoint $service.Spec.Components.Schemas .example.Request }}'`

View File

@@ -1,926 +0,0 @@
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"text/template"
"github.com/Masterminds/semver/v3"
"github.com/fatih/camelcase"
"github.com/getkin/kin-openapi/openapi3"
"github.com/stoewer/go-strcase"
)
type service struct {
Spec *openapi3.Swagger
Name string
// overwrite import name of service when it's a keyword ie function in javascript
ImportName string
}
type example struct {
Title string `json:"title"`
Description string `json:"description"`
Request map[string]interface{}
Response map[string]interface{}
}
func main() {
files, err := ioutil.ReadDir(os.Args[1])
if err != nil {
log.Fatal(err)
}
workDir, _ := os.Getwd()
tsPath := filepath.Join(workDir, "clients", "ts")
err = os.MkdirAll(tsPath, 0777)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
goPath := filepath.Join(workDir, "clients", "go")
err = os.MkdirAll(goPath, 0777)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
examplesPath := filepath.Join(workDir, "examples")
err = os.MkdirAll(goPath, 0777)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
funcs := map[string]interface{}{
"recursiveTypeDefinition": func(language, serviceName, typeName string, schemas map[string]*openapi3.SchemaRef) string {
return schemaToType(language, serviceName, typeName, schemas)
},
"requestTypeToEndpointName": func(requestType string) string {
parts := camelcase.Split(requestType)
return strings.Join(parts[1:len(parts)-1], "")
},
// strips service name from the request type
"requestType": func(requestType string) string {
parts := camelcase.Split(requestType)
return strings.Join(parts[1:], "")
},
"requestTypeToResponseType": func(requestType string) string {
parts := camelcase.Split(requestType)
return strings.Join(parts[1:len(parts)-1], "") + "Response"
},
"endpointComment": func(endpoint string, schemas map[string]*openapi3.SchemaRef) string {
v := schemas[strings.Title(endpoint)+"Request"]
if v == nil {
panic("can't find " + strings.Title(endpoint) + "Request")
}
if v.Value == nil {
return ""
}
comm := v.Value.Description
ret := ""
for _, line := range strings.Split(comm, "\n") {
ret += "// " + strings.TrimSpace(line) + "\n"
}
return ret
},
"requestTypeToEndpointPath": func(requestType string) string {
parts := camelcase.Split(requestType)
return strings.Title(strings.Join(parts[1:len(parts)-1], ""))
},
"title": strings.Title,
"untitle": func(t string) string {
return strcase.LowerCamelCase(t)
},
"goExampleRequest": func(serviceName, endpoint string, schemas map[string]*openapi3.SchemaRef, exampleJSON map[string]interface{}) string {
return schemaToGoExample(serviceName, strings.Title(endpoint)+"Request", schemas, exampleJSON)
},
"tsExampleRequest": func(serviceName, endpoint string, schemas map[string]*openapi3.SchemaRef, exampleJSON map[string]interface{}) string {
bs, _ := json.MarshalIndent(exampleJSON, "", " ")
return string(bs)
},
}
services := []service{}
tsFileList := []string{"esm", "index.js", "index.d.ts"}
for _, f := range files {
if strings.Contains(f.Name(), "clients") || strings.Contains(f.Name(), "examples") {
continue
}
if f.IsDir() && !strings.HasPrefix(f.Name(), ".") {
serviceName := f.Name()
tsFileList = append(tsFileList, serviceName)
serviceDir := filepath.Join(workDir, f.Name())
cmd := exec.Command("make", "api")
cmd.Dir = serviceDir
outp, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(string(outp))
}
serviceFiles, err := ioutil.ReadDir(serviceDir)
if err != nil {
fmt.Println("Failed to read service dir", err)
os.Exit(1)
}
skip := false
// detect openapi json file
apiJSON := ""
for _, serviceFile := range serviceFiles {
if strings.Contains(serviceFile.Name(), "api") && strings.Contains(serviceFile.Name(), "-") && strings.HasSuffix(serviceFile.Name(), ".json") {
apiJSON = filepath.Join(serviceDir, serviceFile.Name())
}
if serviceFile.Name() == "skip" {
skip = true
}
}
if skip {
continue
}
fmt.Println("Processing folder", serviceDir, "api json", apiJSON)
js, err := ioutil.ReadFile(apiJSON)
if err != nil {
fmt.Println("Failed to read json spec", err)
os.Exit(1)
}
spec := &openapi3.Swagger{}
err = json.Unmarshal(js, &spec)
if err != nil {
fmt.Println("Failed to unmarshal", err)
os.Exit(1)
}
service := service{
Name: serviceName,
ImportName: serviceName,
Spec: spec,
}
if service.Name == "function" {
service.ImportName = "fx"
}
services = append(services, service)
templ, err := template.New("ts" + serviceName).Funcs(funcs).Parse(tsServiceTemplate)
if err != nil {
fmt.Println("Failed to unmarshal", err)
os.Exit(1)
}
var b bytes.Buffer
buf := bufio.NewWriter(&b)
err = templ.Execute(buf, map[string]interface{}{
"service": service,
})
if err != nil {
fmt.Println("Failed to unmarshal", err)
os.Exit(1)
}
err = os.MkdirAll(filepath.Join(tsPath, "src", serviceName), 0777)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
f, err := os.OpenFile(filepath.Join(tsPath, "src", serviceName, "index.ts"), os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0744)
if err != nil {
fmt.Println("Failed to open schema file", err)
os.Exit(1)
}
buf.Flush()
_, err = f.Write(b.Bytes())
if err != nil {
fmt.Println("Failed to append to schema file", err)
os.Exit(1)
}
cmd = exec.Command("prettier", "-w", "index.ts")
cmd.Dir = filepath.Join(tsPath, "src", serviceName)
outp, err = cmd.CombinedOutput()
if err != nil {
fmt.Println(fmt.Sprintf("Problem formatting '%v' client: %v %s", serviceName, string(outp), err.Error()))
os.Exit(1)
}
templ, err = template.New("go" + serviceName).Funcs(funcs).Parse(goServiceTemplate)
if err != nil {
fmt.Println("Failed to unmarshal", err)
os.Exit(1)
}
b = bytes.Buffer{}
buf = bufio.NewWriter(&b)
err = templ.Execute(buf, map[string]interface{}{
"service": service,
})
if err != nil {
fmt.Println("Failed to unmarshal", err)
os.Exit(1)
}
err = os.MkdirAll(filepath.Join(goPath, serviceName), 0777)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
goClientFile := filepath.Join(goPath, serviceName, serviceName+".go")
f, err = os.OpenFile(goClientFile, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0744)
if err != nil {
fmt.Println("Failed to open schema file", err)
os.Exit(1)
}
buf.Flush()
_, err = f.Write(b.Bytes())
if err != nil {
fmt.Println("Failed to append to schema file", err)
os.Exit(1)
}
cmd = exec.Command("gofmt", "-w", serviceName+".go")
cmd.Dir = filepath.Join(goPath, serviceName)
outp, err = cmd.CombinedOutput()
if err != nil {
fmt.Println(fmt.Sprintf("Problem formatting '%v' client: %v", serviceName, string(outp)))
os.Exit(1)
}
cmd = exec.Command("go", "build", "-o", "/tmp/bin/outputfile")
cmd.Dir = filepath.Join(goPath, serviceName)
outp, err = cmd.CombinedOutput()
if err != nil {
fmt.Println(fmt.Sprintf("Problem building '%v' example: %v", serviceName, string(outp)))
os.Exit(1)
}
exam, err := ioutil.ReadFile(filepath.Join(workDir, serviceName, "examples.json"))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if err == nil {
m := map[string][]example{}
err = json.Unmarshal(exam, &m)
if err != nil {
fmt.Println(string(exam), err)
os.Exit(1)
}
if len(service.Spec.Paths) != len(m) {
fmt.Printf("Service has %v endpoints, but only %v examples\n", len(service.Spec.Paths), len(m))
}
for endpoint, examples := range m {
for _, example := range examples {
title := regexp.MustCompile("[^a-zA-Z0-9]+").ReplaceAllString(strcase.LowerCamelCase(strings.Replace(example.Title, " ", "_", -1)), "")
templ, err = template.New("go" + serviceName + endpoint).Funcs(funcs).Parse(goExampleTemplate)
if err != nil {
fmt.Println("Failed to unmarshal", err)
os.Exit(1)
}
b = bytes.Buffer{}
buf = bufio.NewWriter(&b)
err = templ.Execute(buf, map[string]interface{}{
"service": service,
"example": example,
"endpoint": endpoint,
"funcName": strcase.UpperCamelCase(title),
})
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// create go examples directory
err = os.MkdirAll(filepath.Join(examplesPath, serviceName, endpoint, "go"), 0777)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
goExampleFile := filepath.Join(examplesPath, serviceName, endpoint, "go", title+".go")
f, err = os.OpenFile(goExampleFile, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0744)
if err != nil {
fmt.Println("Failed to open schema file", err)
os.Exit(1)
}
buf.Flush()
_, err = f.Write(b.Bytes())
if err != nil {
fmt.Println("Failed to append to schema file", err)
os.Exit(1)
}
cmd := exec.Command("gofmt", "-w", title+".go")
cmd.Dir = filepath.Join(examplesPath, serviceName, endpoint, "go")
outp, err = cmd.CombinedOutput()
if err != nil {
fmt.Println(fmt.Sprintf("Problem with '%v' example '%v': %v", serviceName, endpoint, string(outp)))
os.Exit(1)
}
// node example
templ, err = template.New("ts" + serviceName + endpoint).Funcs(funcs).Parse(tsExampleTemplate)
if err != nil {
fmt.Println("Failed to unmarshal", err)
os.Exit(1)
}
b = bytes.Buffer{}
buf = bufio.NewWriter(&b)
err = templ.Execute(buf, map[string]interface{}{
"service": service,
"example": example,
"endpoint": endpoint,
"funcName": strcase.UpperCamelCase(title),
})
err = os.MkdirAll(filepath.Join(examplesPath, serviceName, endpoint, "node"), 0777)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
tsExampleFile := filepath.Join(examplesPath, serviceName, endpoint, "node", title+".js")
f, err = os.OpenFile(tsExampleFile, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0744)
if err != nil {
fmt.Println("Failed to open schema file", err)
os.Exit(1)
}
buf.Flush()
_, err = f.Write(b.Bytes())
if err != nil {
fmt.Println("Failed to append to schema file", err)
os.Exit(1)
}
cmd = exec.Command("prettier", "-w", title+".js")
cmd.Dir = filepath.Join(examplesPath, serviceName, endpoint, "node")
outp, err = cmd.CombinedOutput()
if err != nil {
fmt.Println(fmt.Sprintf("Problem with '%v' example '%v': %v", serviceName, endpoint, string(outp)))
os.Exit(1)
}
// curl example
templ, err = template.New("curl" + serviceName + endpoint).Funcs(funcs).Parse(curlExampleTemplate)
if err != nil {
fmt.Println("Failed to unmarshal", err)
os.Exit(1)
}
b = bytes.Buffer{}
buf = bufio.NewWriter(&b)
err = templ.Execute(buf, map[string]interface{}{
"service": service,
"example": example,
"endpoint": endpoint,
"funcName": strcase.UpperCamelCase(title),
})
err = os.MkdirAll(filepath.Join(examplesPath, serviceName, endpoint, "curl"), 0777)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
curlExampleFile := filepath.Join(examplesPath, serviceName, endpoint, "curl", title+".sh")
f, err = os.OpenFile(curlExampleFile, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0744)
if err != nil {
fmt.Println("Failed to open schema file", err)
os.Exit(1)
}
buf.Flush()
_, err = f.Write(b.Bytes())
if err != nil {
fmt.Println("Failed to append to schema file", err)
os.Exit(1)
}
}
// only build after each example is generated as old files from
// previous generation might not compile
cmd = exec.Command("go", "build", "-o", "/tmp/bin/outputfile")
cmd.Dir = filepath.Join(examplesPath, serviceName, endpoint, "go")
outp, err = cmd.CombinedOutput()
if err != nil {
fmt.Println(fmt.Sprintf("Problem with '%v' example '%v': %v", serviceName, endpoint, string(outp)))
os.Exit(1)
}
}
} else {
fmt.Println(err)
}
}
}
templ, err := template.New("tsclient").Funcs(funcs).Parse(tsIndexTemplate)
if err != nil {
fmt.Println("Failed to unmarshal", err)
os.Exit(1)
}
var b bytes.Buffer
buf := bufio.NewWriter(&b)
err = templ.Execute(buf, map[string]interface{}{
"services": services,
})
if err != nil {
fmt.Println("Failed to unmarshal", err)
os.Exit(1)
}
f, err := os.OpenFile(filepath.Join(tsPath, "index.ts"), os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0744)
if err != nil {
fmt.Println("Failed to open schema file", err)
os.Exit(1)
}
buf.Flush()
_, err = f.Write(b.Bytes())
if err != nil {
fmt.Println("Failed to append to schema file", err)
os.Exit(1)
}
cmd := exec.Command("prettier", "-w", "index.ts")
cmd.Dir = filepath.Join(tsPath)
outp, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(fmt.Sprintf("Problem with prettifying clients index.ts '%v", string(outp)))
os.Exit(1)
}
tsFiles := filepath.Join(workDir, "cmd", "clients", "ts")
cmd = exec.Command("cp", filepath.Join(tsFiles, "package.json"), filepath.Join(tsFiles, ".gitignore"), filepath.Join(tsFiles, "package-lock.json"), filepath.Join(tsFiles, "package-lock.json"), filepath.Join(tsFiles, "build.js"), filepath.Join(tsFiles, "tsconfig.es.json"), filepath.Join(tsFiles, "package-lock.json"), filepath.Join(tsFiles, "tsconfig.json"), filepath.Join(workDir, "clients", "ts"))
cmd.Dir = filepath.Join(tsPath)
outp, err = cmd.CombinedOutput()
if err != nil {
fmt.Println(fmt.Sprintf("Problem with prettifying clients index.ts '%v", string(outp)))
os.Exit(1)
}
templ, err = template.New("goclient").Funcs(funcs).Parse(goIndexTemplate)
if err != nil {
fmt.Println("Failed to unmarshal", err)
os.Exit(1)
}
b = bytes.Buffer{}
buf = bufio.NewWriter(&b)
err = templ.Execute(buf, map[string]interface{}{
"services": services,
})
if err != nil {
fmt.Println("Failed to unmarshal", err)
os.Exit(1)
}
f, err = os.OpenFile(filepath.Join(goPath, "m3o.go"), os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0744)
if err != nil {
fmt.Println("Failed to open schema file", err)
os.Exit(1)
}
buf.Flush()
_, err = f.Write(b.Bytes())
if err != nil {
fmt.Println("Failed to append to schema file", err)
os.Exit(1)
}
cmd = exec.Command("gofmt", "-w", "m3o.go")
cmd.Dir = filepath.Join(goPath)
outp, err = cmd.CombinedOutput()
if err != nil {
fmt.Println(fmt.Sprintf("Problem with formatting m3o.go '%v", string(outp)))
os.Exit(1)
}
cmd = exec.Command("go", "build", "-o", "/tmp/bin/outputfile")
cmd.Dir = filepath.Join(goPath)
outp, err = cmd.CombinedOutput()
if err != nil {
fmt.Println(fmt.Sprintf("Problem building m3o.go '%v'", string(outp)))
os.Exit(1)
}
// login to NPM
f, err = os.OpenFile(filepath.Join(tsPath, ".npmrc"), os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
fmt.Println("Failed to open npmrc", err)
os.Exit(1)
}
defer f.Close()
if len(os.Getenv("NPM_TOKEN")) == 0 {
fmt.Println("No NPM_TOKEN env found")
os.Exit(1)
}
if _, err = f.WriteString("//registry.npmjs.org/:_authToken=" + os.Getenv("NPM_TOKEN")); err != nil {
fmt.Println("Failed to open npmrc", err)
os.Exit(1)
}
// get latest version from github
getVersions := exec.Command("npm", "show", "m3o", "--time", "--json")
getVersions.Dir = tsPath
outp, err = getVersions.CombinedOutput()
if err != nil {
fmt.Println("Failed to get versions of NPM package", string(outp))
os.Exit(1)
}
type npmVers struct {
Versions []string `json:"versions"`
}
beta := os.Getenv("IS_BETA") != ""
if beta {
fmt.Println("creating beta version")
} else {
fmt.Println("creating live version")
}
npmOutput := &npmVers{}
var latest *semver.Version
if len(outp) > 0 {
err = json.Unmarshal(outp, npmOutput)
if err != nil {
fmt.Println("Failed to unmarshal versions", string(outp))
os.Exit(1)
}
}
fmt.Println("npm output version: ", npmOutput.Versions)
for _, version := range npmOutput.Versions {
v, err := semver.NewVersion(version)
if err != nil {
fmt.Println("Failed to parse semver", err)
os.Exit(1)
}
if latest == nil {
latest = v
}
if v.GreaterThan(latest) {
latest = v
}
}
if latest == nil {
fmt.Println("found no semver version")
os.Exit(1)
}
var newV semver.Version
if beta {
// bump a beta version
if strings.Contains(latest.String(), "beta") {
newV = incBeta(*latest)
} else {
// make beta out of latest non beta version
v, _ := semver.NewVersion(latest.IncPatch().String() + "-beta1")
newV = *v
}
} else {
newV = latest.IncPatch()
}
// add file list to gitignore
f, err = os.OpenFile(filepath.Join(tsPath, ".gitignore"), os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0744)
for _, sname := range tsFileList {
_, err := f.Write([]byte(sname + "\n"))
if err != nil {
fmt.Println("failed to append service to gitignore", err)
os.Exit(1)
}
}
// bump package to latest version
fmt.Println("Bumping to ", newV.String())
repl := exec.Command("sed", "-i", "-e", "s/1.0.1/"+newV.String()+"/g", "package.json")
repl.Dir = tsPath
outp, err = repl.CombinedOutput()
if err != nil {
fmt.Println("Failed to make docs", string(outp))
os.Exit(1)
}
// apppend exports to to package.json
pak, err := ioutil.ReadFile(filepath.Join(tsPath, "package.json"))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
m := map[string]interface{}{}
err = json.Unmarshal(pak, &m)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
m["files"] = tsFileList
pakJS, err := json.MarshalIndent(m, "", " ")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
f, err = os.OpenFile(filepath.Join(tsPath, "package.json"), os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0744)
if err != nil {
fmt.Println("Failed to open package.json", err)
os.Exit(1)
}
_, err = f.Write(pakJS)
if err != nil {
fmt.Println("Failed to write to package.json", err)
os.Exit(1)
}
}
func incBeta(ver semver.Version) semver.Version {
s := ver.String()
parts := strings.Split(s, "beta")
if len(parts) < 2 {
panic("not a beta version " + s)
}
i, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil {
panic(err)
}
i++
v, err := semver.NewVersion(parts[0] + "beta" + fmt.Sprintf("%v", i))
if err != nil {
panic(err)
}
return *v
}
func schemaToType(language, serviceName, typeName string, schemas map[string]*openapi3.SchemaRef) string {
var recurse func(props map[string]*openapi3.SchemaRef, level int) string
var spec *openapi3.SchemaRef = schemas[typeName]
detectType := func(currentType string, properties map[string]*openapi3.SchemaRef) (string, bool) {
index := map[string]bool{}
for key, prop := range properties {
index[key+prop.Value.Title+prop.Value.Description] = true
}
for k, schema := range schemas {
// we don't want to return the type matching itself
if strings.ToLower(k) == currentType {
continue
}
if strings.HasSuffix(k, "Request") || strings.HasSuffix(k, "Response") {
continue
}
if len(schema.Value.Properties) != len(properties) {
continue
}
found := false
for key, prop := range schema.Value.Properties {
_, ok := index[key+prop.Value.Title+prop.Value.Description]
found = ok
if !ok {
break
}
}
if found {
return schema.Value.Title, true
}
}
return "", false
}
var fieldSeparator, arrayPrefix, arrayPostfix, fieldDelimiter, stringType, numberType, boolType string
var int32Type, int64Type, floatType, doubleType, mapType, anyType, typePrefix string
var fieldUpperCase bool
switch language {
case "typescript":
fieldUpperCase = false
fieldSeparator = "?: "
arrayPrefix = ""
arrayPostfix = "[]"
//objectOpen = "{\n"
//objectClose = "}"
fieldDelimiter = ";"
stringType = "string"
numberType = "number"
boolType = "boolean"
int32Type = "number"
int64Type = "number"
floatType = "number"
doubleType = "number"
anyType = "any"
mapType = "{ [key: string]: %v }"
typePrefix = ""
case "go":
fieldUpperCase = true
fieldSeparator = " "
arrayPrefix = "[]"
arrayPostfix = ""
//objectOpen = "{"
// objectClose = "}"
fieldDelimiter = ""
stringType = "string"
numberType = "int64"
boolType = "bool"
int32Type = "int32"
int64Type = "int64"
floatType = "float32"
doubleType = "float64"
mapType = "map[string]%v"
anyType = "interface{}"
typePrefix = "*"
}
valueToType := func(v *openapi3.SchemaRef) string {
switch v.Value.Type {
case "string":
return stringType
case "boolean":
return boolType
case "number":
switch v.Value.Format {
case "int32":
return int32Type
case "int64":
return int64Type
case "float":
return floatType
case "double":
return doubleType
}
default:
return "unrecognized: " + v.Value.Type
}
return ""
}
recurse = func(props map[string]*openapi3.SchemaRef, level int) string {
ret := ""
i := 0
var keys []string
for k := range props {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := props[k]
ret += strings.Repeat(" ", level)
if v.Value.Description != "" {
for _, commentLine := range strings.Split(v.Value.Description, "\n") {
ret += "// " + strings.TrimSpace(commentLine) + "\n" + strings.Repeat(" ", level)
}
}
if fieldUpperCase {
k = strcase.UpperCamelCase(k)
}
var typ string
// @todo clean up this piece of code by
// separating out type string marshaling and not
// repeating code
switch v.Value.Type {
case "object":
typ, found := detectType(k, v.Value.Properties)
if found {
ret += k + fieldSeparator + typePrefix + strings.Title(typ) + fieldDelimiter
} else {
// type is a dynamic map
// if additional properties is not present, it's an any type,
// like the proto struct type
if v.Value.AdditionalProperties != nil {
ret += k + fieldSeparator + fmt.Sprintf(mapType, valueToType(v.Value.AdditionalProperties)) + fieldDelimiter
} else {
ret += k + fieldSeparator + fmt.Sprintf(mapType, anyType) + fieldDelimiter
}
}
case "array":
typ, found := detectType(k, v.Value.Items.Value.Properties)
if found {
ret += k + fieldSeparator + arrayPrefix + strings.Title(typ) + arrayPostfix + fieldDelimiter
} else {
switch v.Value.Items.Value.Type {
case "string":
ret += k + fieldSeparator + arrayPrefix + stringType + arrayPostfix + fieldDelimiter
case "number":
typ := numberType
switch v.Value.Format {
case "int32":
typ = int32Type
case "int64":
typ = int64Type
case "float":
typ = floatType
case "double":
typ = doubleType
}
ret += k + fieldSeparator + arrayPrefix + typ + arrayPostfix + fieldDelimiter
case "boolean":
ret += k + fieldSeparator + arrayPrefix + boolType + arrayPostfix + fieldDelimiter
case "object":
// type is a dynamic map
// if additional properties is not present, it's an any type,
// like the proto struct type
if v.Value.AdditionalProperties != nil {
ret += k + fieldSeparator + arrayPrefix + fmt.Sprintf(mapType, valueToType(v.Value.AdditionalProperties)) + arrayPostfix + fieldDelimiter
} else {
ret += k + fieldSeparator + arrayPrefix + fmt.Sprintf(mapType, anyType) + arrayPostfix + fieldDelimiter
}
}
}
case "string":
ret += k + fieldSeparator + stringType + fieldDelimiter
case "number":
typ = numberType
switch v.Value.Format {
case "int32":
typ = int32Type
case "int64":
typ = int64Type
case "float":
typ = floatType
case "double":
typ = doubleType
}
ret += k + fieldSeparator + typ + fieldDelimiter
case "boolean":
ret += k + fieldSeparator + boolType + fieldDelimiter
}
// go specific hack for lowercase json
if language == "go" {
ret += " " + "`json:\"" + strcase.LowerCamelCase(k)
if typ == int64Type {
ret += ",string"
}
ret += "\"`"
}
if i < len(props) {
ret += "\n"
}
i++
}
return ret
}
return recurse(spec.Value.Properties, 1)
}
func schemaToMethods(title string, spec *openapi3.RequestBodyRef) string {
return ""
}
// CopyFile copies a file from src to dst. If src and dst files exist, and are
// the same, then return success. Otherise, attempt to create a hard link
// between the two files. If that fail, copy the file contents from src to dst.
// from https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
func CopyFile(src, dst string) (err error) {
sfi, err := os.Stat(src)
if err != nil {
return
}
if !sfi.Mode().IsRegular() {
// cannot copy non-regular files (e.g., directories,
// symlinks, devices, etc.)
return fmt.Errorf("CopyFile: non-regular source file %s (%q)", sfi.Name(), sfi.Mode().String())
}
dfi, err := os.Stat(dst)
if err != nil {
if !os.IsNotExist(err) {
return
}
} else {
if !(dfi.Mode().IsRegular()) {
return fmt.Errorf("CopyFile: non-regular destination file %s (%q)", dfi.Name(), dfi.Mode().String())
}
if os.SameFile(sfi, dfi) {
return
}
}
if err = os.Link(src, dst); err == nil {
return
}
err = copyFileContents(src, dst)
return
}
// copyFileContents copies the contents of the file named src to the file named
// by dst. The file will be created if it does not already exist. If the
// destination file exists, all it's contents will be replaced by the contents
// of the source file.
func copyFileContents(src, dst string) (err error) {
in, err := os.Open(src)
if err != nil {
return
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return
}
defer func() {
cerr := out.Close()
if err == nil {
err = cerr
}
}()
if _, err = io.Copy(out, in); err != nil {
return
}
err = out.Sync()
return
}

View File

@@ -1,10 +0,0 @@
node_modules
dist
es
lib
types
tmp
index.js
index.d.ts
esm
.npmrc

Some files were not shown because too many files have changed in this diff Show More