How to Create Arrays in Python

In this tutorial, you'll know the basics of how to create arrays in Python using the array module. Learn how to use Python arrays. You'll see how to define them and the different methods commonly used for performing operations on them.

This tutorialvideo on 'Arrays in Python' will help you establish a strong hold on all the fundamentals in python programming language. Below are the topics covered in this video:  
1:15 What is an array?
2:53 Is python list same as an array?
3:48  How to create arrays in python?
7:19 Accessing array elements
9:59 Basic array operations
        - 10:33  Finding the length of an array
        - 11:44  Adding Elements
        - 15:06  Removing elements
        - 18:32  Array concatenation
       - 20:59  Slicing
       - 23:26  Looping  


Python Array Tutorial – Define, Index, Methods

In this article, you'll learn how to use Python arrays. You'll see how to define them and the different methods commonly used for performing operations on them.

The artcile covers arrays that you create by importing the array module. We won't cover NumPy arrays here.

Table of Contents

  1. Introduction to Arrays
    1. The differences between Lists and Arrays
    2. When to use arrays
  2. How to use arrays
    1. Define arrays
    2. Find the length of arrays
    3. Array indexing
    4. Search through arrays
    5. Loop through arrays
    6. Slice an array
  3. Array methods for performing operations
    1. Change an existing value
    2. Add a new value
    3. Remove a value
  4. Conclusion

Let's get started!

What are Python Arrays?

Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time.

Specifically, they are an ordered collection of elements with every value being of the same data type. That is the most important thing to remember about Python arrays - the fact that they can only hold a sequence of multiple items that are of the same type.

What's the Difference between Python Lists and Python Arrays?

Lists are one of the most common data structures in Python, and a core part of the language.

Lists and arrays behave similarly.

Just like arrays, lists are an ordered sequence of elements.

They are also mutable and not fixed in size, which means they can grow and shrink throughout the life of the program. Items can be added and removed, making them very flexible to work with.

However, lists and arrays are not the same thing.

Lists store items that are of various data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type, at the same time. That is not the case with arrays.

As mentioned in the section above, arrays store only items that are of the same single data type. There are arrays that contain only integers, or only floating point numbers, or only any other Python data type you want to use.

When to Use Python Arrays

Lists are built into the Python programming language, whereas arrays aren't. Arrays are not a built-in data structure, and therefore need to be imported via the array module in order to be used.

Arrays of the array module are a thin wrapper over C arrays, and are useful when you want to work with homogeneous data.

They are also more compact and take up less memory and space which makes them more size efficient compared to lists.

If you want to perform mathematical calculations, then you should use NumPy arrays by importing the NumPy package. Besides that, you should just use Python arrays when you really need to, as lists work in a similar way and are more flexible to work with.

How to Use Arrays in Python

In order to create Python arrays, you'll first have to import the array module which contains all the necassary functions.

There are three ways you can import the array module:

  • By using import array at the top of the file. This includes the module array. You would then go on to create an array using array.array().
import array

#how you would create an array
array.array()
  • Instead of having to type array.array() all the time, you could use import array as arr at the top of the file, instead of import array alone. You would then create an array by typing arr.array(). The arr acts as an alias name, with the array constructor then immediately following it.
import array as arr

#how you would create an array
arr.array()
  • Lastly, you could also use from array import *, with * importing all the functionalities available. You would then create an array by writing the array() constructor alone.
from array import *

#how you would create an array
array()

How to Define Arrays in Python

Once you've imported the array module, you can then go on to define a Python array.

The general syntax for creating an array looks like this:

variable_name = array(typecode,[elements])

Let's break it down:

  • variable_name would be the name of the array.
  • The typecode specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type.
  • Inside square brackets you mention the elements that would be stored in the array, with each element being separated by a comma. You can also create an empty array by just writing variable_name = array(typecode) alone, without any elements.

Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays:

TYPECODEC TYPEPYTHON TYPESIZE
'b'signed charint1
'B'unsigned charint1
'u'wchar_tUnicode character2
'h'signed shortint2
'H'unsigned shortint2
'i'signed intint2
'I'unsigned intint2
'l'signed longint4
'L'unsigned longint4
'q'signed long longint8
'Q'unsigned long longint8
'f'floatfloat4
'd'doublefloat8

Tying everything together, here is an example of how you would define an array in Python:

import array as arr 

numbers = arr.array('i',[10,20,30])


print(numbers)

#output

#array('i', [10, 20, 30])

Let's break it down:

  • First we included the array module, in this case with import array as arr .
  • Then, we created a numbers array.
  • We used arr.array() because of import array as arr .
  • Inside the array() constructor, we first included i, for signed integer. Signed integer means that the array can include positive and negative values. Unsigned integer, with H for example, would mean that no negative values are allowed.
  • Lastly, we included the values to be stored in the array in square brackets.

Keep in mind that if you tried to include values that were not of i typecode, meaning they were not integer values, you would get an error:

import array as arr 

numbers = arr.array('i',[10.0,20,30])


print(numbers)

#output

#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
#   numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer

In the example above, I tried to include a floating point number in the array. I got an error because this is meant to be an integer array only.

Another way to create an array is the following:

from array import *

#an array of floating point values
numbers = array('d',[10.0,20.0,30.0])

print(numbers)

#output

#array('d', [10.0, 20.0, 30.0])

The example above imported the array module via from array import * and created an array numbers of float data type. This means that it holds only floating point numbers, which is specified with the 'd' typecode.

How to Find the Length of an Array in Python

To find out the exact number of elements contained in an array, use the built-in len() method.

It will return the integer number that is equal to the total number of elements in the array you specify.

import array as arr 

numbers = arr.array('i',[10,20,30])


print(len(numbers))

#output
# 3

In the example above, the array contained three elements – 10, 20, 30 – so the length of numbers is 3.

Array Indexing and How to Access Individual Items in an Array in Python

Each item in an array has a specific address. Individual items are accessed by referencing their index number.

Indexing in Python, and in all programming languages and computing in general, starts at 0. It is important to remember that counting starts at 0 and not at 1.

To access an element, you first write the name of the array followed by square brackets. Inside the square brackets you include the item's index number.

The general syntax would look something like this:

array_name[index_value_of_item]

Here is how you would access each individual element in an array:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element

#output

#10
#20
#30

Remember that the index value of the last element of an array is always one less than the length of the array. Where n is the length of the array, n - 1 will be the index value of the last item.

Note that you can also access each individual element using negative indexing.

With negative indexing, the last element would have an index of -1, the second to last element would have an index of -2, and so on.

Here is how you would get each item in an array using that method:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
 
#output

#30
#20
#10

How to Search Through an Array in Python

You can find out an element's index number by using the index() method.

You pass the value of the element being searched as the argument to the method, and the element's index number is returned.

import array as arr 

numbers = arr.array('i',[10,20,30])

#search for the index of the value 10
print(numbers.index(10))

#output

#0

If there is more than one element with the same value, the index of the first instance of the value will be returned:

import array as arr 


numbers = arr.array('i',[10,20,30,10,20,30])

#search for the index of the value 10
#will return the index number of the first instance of the value 10
print(numbers.index(10))

#output

#0

How to Loop through an Array in Python

You've seen how to access each individual element in an array and print it out on its own.

You've also seen how to print the array, using the print() method. That method gives the following result:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers)

#output

#array('i', [10, 20, 30])

What if you want to print each value one by one?

This is where a loop comes in handy. You can loop through the array and print out each value, one-by-one, with each loop iteration.

For this you can use a simple for loop:

import array as arr 

numbers = arr.array('i',[10,20,30])

for number in numbers:
    print(number)
    
#output
#10
#20
#30

You could also use the range() function, and pass the len() method as its parameter. This would give the same result as above:

import array as arr  

values = arr.array('i',[10,20,30])

#prints each individual value in the array
for value in range(len(values)):
    print(values[value])

#output

#10
#20
#30

How to Slice an Array in Python

To access a specific range of values inside the array, use the slicing operator, which is a colon :.

When using the slicing operator and you only include one value, the counting starts from 0 by default. It gets the first item, and goes up to but not including the index number you specify.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#get the values 10 and 20 only
print(numbers[:2])  #first to second position

#output

#array('i', [10, 20])

When you pass two numbers as arguments, you specify a range of numbers. In this case, the counting starts at the position of the first number in the range, and up to but not including the second one:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])


#get the values 20 and 30 only
print(numbers[1:3]) #second to third position

#output

#rray('i', [20, 30])

Methods For Performing Operations on Arrays in Python

Arrays are mutable, which means they are changeable. You can change the value of the different items, add new ones, or remove any you don't want in your program anymore.

Let's see some of the most commonly used methods which are used for performing operations on arrays.

How to Change the Value of an Item in an Array

You can change the value of a specific element by speficying its position and assigning it a new value:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40

print(numbers)

#output

#array('i', [40, 20, 30])

How to Add a New Value to an Array

To add one single value at the end of an array, use the append() method:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40)

print(numbers)

#output

#array('i', [10, 20, 30, 40])

Be aware that the new item you add needs to be the same data type as the rest of the items in the array.

Look what happens when I try to add a float to an array of integers:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40.0)

print(numbers)

#output

#Traceback (most recent call last):
#  File "/Users/dionysialemonaki/python_articles/demo.py", line 19, in <module>
#   numbers.append(40.0)
#TypeError: 'float' object cannot be interpreted as an integer

But what if you want to add more than one value to the end an array?

Use the extend() method, which takes an iterable (such as a list of items) as an argument. Again, make sure that the new items are all the same data type.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integers 40,50,60 to the end of numbers
#The numbers need to be enclosed in square brackets

numbers.extend([40,50,60])

print(numbers)

#output

#array('i', [10, 20, 30, 40, 50, 60])

And what if you don't want to add an item to the end of an array? Use the insert() method, to add an item at a specific position.

The insert() function takes two arguments: the index number of the position the new element will be inserted, and the value of the new element.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 in the first position
#remember indexing starts at 0

numbers.insert(0,40)

print(numbers)

#output

#array('i', [40, 10, 20, 30])

How to Remove a Value from an Array

To remove an element from an array, use the remove() method and include the value as an argument to the method.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30])

With remove(), only the first instance of the value you pass as an argument will be removed.

See what happens when there are more than one identical values:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Only the first occurence of 10 is removed.

You can also use the pop() method, and specify the position of the element to be removed:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

#remove the first instance of 10
numbers.pop(0)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Conclusion

And there you have it - you now know the basics of how to create arrays in Python using the array module. Hopefully you found this guide helpful.

Thanks for reading and happy coding!

#python #programming 

Shubham Ankit

Shubham Ankit

1657081614

How to Automate Excel with Python | Python Excel Tutorial (OpenPyXL)

How to Automate Excel with Python

In this article, We will show how we can use python to automate Excel . A useful Python library is Openpyxl which we will learn to do Excel Automation

What is OPENPYXL

Openpyxl is a Python library that is used to read from an Excel file or write to an Excel file. Data scientists use Openpyxl for data analysis, data copying, data mining, drawing charts, styling sheets, adding formulas, and more.

Workbook: A spreadsheet is represented as a workbook in openpyxl. A workbook consists of one or more sheets.

Sheet: A sheet is a single page composed of cells for organizing data.

Cell: The intersection of a row and a column is called a cell. Usually represented by A1, B5, etc.

Row: A row is a horizontal line represented by a number (1,2, etc.).

Column: A column is a vertical line represented by a capital letter (A, B, etc.).

Openpyxl can be installed using the pip command and it is recommended to install it in a virtual environment.

pip install openpyxl

CREATE A NEW WORKBOOK

We start by creating a new spreadsheet, which is called a workbook in Openpyxl. We import the workbook module from Openpyxl and use the function Workbook() which creates a new workbook.

from openpyxl
import Workbook
#creates a new workbook
wb = Workbook()
#Gets the first active worksheet
ws = wb.active
#creating new worksheets by using the create_sheet method

ws1 = wb.create_sheet("sheet1", 0) #inserts at first position
ws2 = wb.create_sheet("sheet2") #inserts at last position
ws3 = wb.create_sheet("sheet3", -1) #inserts at penultimate position

#Renaming the sheet
ws.title = "Example"

#save the workbook
wb.save(filename = "example.xlsx")

READING DATA FROM WORKBOOK

We load the file using the function load_Workbook() which takes the filename as an argument. The file must be saved in the same working directory.

#loading a workbook
wb = openpyxl.load_workbook("example.xlsx")

 

GETTING SHEETS FROM THE LOADED WORKBOOK

 

#getting sheet names
wb.sheetnames
result = ['sheet1', 'Sheet', 'sheet3', 'sheet2']

#getting a particular sheet
sheet1 = wb["sheet2"]

#getting sheet title
sheet1.title
result = 'sheet2'

#Getting the active sheet
sheetactive = wb.active
result = 'sheet1'

 

ACCESSING CELLS AND CELL VALUES

 

#get a cell from the sheet
sheet1["A1"] <
  Cell 'Sheet1'.A1 >

  #get the cell value
ws["A1"].value 'Segment'

#accessing cell using row and column and assigning a value
d = ws.cell(row = 4, column = 2, value = 10)
d.value
10

 

ITERATING THROUGH ROWS AND COLUMNS

 

#looping through each row and column
for x in range(1, 5):
  for y in range(1, 5):
  print(x, y, ws.cell(row = x, column = y)
    .value)

#getting the highest row number
ws.max_row
701

#getting the highest column number
ws.max_column
19

There are two functions for iterating through rows and columns.

Iter_rows() => returns the rows
Iter_cols() => returns the columns {
  min_row = 4, max_row = 5, min_col = 2, max_col = 5
} => This can be used to set the boundaries
for any iteration.

Example:

#iterating rows
for row in ws.iter_rows(min_row = 2, max_col = 3, max_row = 3):
  for cell in row:
  print(cell) <
  Cell 'Sheet1'.A2 >
  <
  Cell 'Sheet1'.B2 >
  <
  Cell 'Sheet1'.C2 >
  <
  Cell 'Sheet1'.A3 >
  <
  Cell 'Sheet1'.B3 >
  <
  Cell 'Sheet1'.C3 >

  #iterating columns
for col in ws.iter_cols(min_row = 2, max_col = 3, max_row = 3):
  for cell in col:
  print(cell) <
  Cell 'Sheet1'.A2 >
  <
  Cell 'Sheet1'.A3 >
  <
  Cell 'Sheet1'.B2 >
  <
  Cell 'Sheet1'.B3 >
  <
  Cell 'Sheet1'.C2 >
  <
  Cell 'Sheet1'.C3 >

To get all the rows of the worksheet we use the method worksheet.rows and to get all the columns of the worksheet we use the method worksheet.columns. Similarly, to iterate only through the values we use the method worksheet.values.


Example:

for row in ws.values:
  for value in row:
  print(value)

 

WRITING DATA TO AN EXCEL FILE

Writing to a workbook can be done in many ways such as adding a formula, adding charts, images, updating cell values, inserting rows and columns, etc… We will discuss each of these with an example.

 

CREATING AND SAVING A NEW WORKBOOK

 

#creates a new workbook
wb = openpyxl.Workbook()

#saving the workbook
wb.save("new.xlsx")

 

ADDING AND REMOVING SHEETS

 

#creating a new sheet
ws1 = wb.create_sheet(title = "sheet 2")

#creating a new sheet at index 0
ws2 = wb.create_sheet(index = 0, title = "sheet 0")

#checking the sheet names
wb.sheetnames['sheet 0', 'Sheet', 'sheet 2']

#deleting a sheet
del wb['sheet 0']

#checking sheetnames
wb.sheetnames['Sheet', 'sheet 2']

 

ADDING CELL VALUES

 

#checking the sheet value
ws['B2'].value
null

#adding value to cell
ws['B2'] = 367

#checking value
ws['B2'].value
367

 

ADDING FORMULAS

 

We often require formulas to be included in our Excel datasheet. We can easily add formulas using the Openpyxl module just like you add values to a cell.
 

For example:

import openpyxl
from openpyxl
import Workbook

wb = openpyxl.load_workbook("new1.xlsx")
ws = wb['Sheet']

ws['A9'] = '=SUM(A2:A8)'

wb.save("new2.xlsx")

The above program will add the formula (=SUM(A2:A8)) in cell A9. The result will be as below.

image

 

MERGE/UNMERGE CELLS

Two or more cells can be merged to a rectangular area using the method merge_cells(), and similarly, they can be unmerged using the method unmerge_cells().

For example:
Merge cells

#merge cells B2 to C9
ws.merge_cells('B2:C9')
ws['B2'] = "Merged cells"

Adding the above code to the previous example will merge cells as below.

image

UNMERGE CELLS

 

#unmerge cells B2 to C9
ws.unmerge_cells('B2:C9')

The above code will unmerge cells from B2 to C9.

INSERTING AN IMAGE

To insert an image we import the image function from the module openpyxl.drawing.image. We then load our image and add it to the cell as shown in the below example.

Example:

import openpyxl
from openpyxl
import Workbook
from openpyxl.drawing.image
import Image

wb = openpyxl.load_workbook("new1.xlsx")
ws = wb['Sheet']
#loading the image(should be in same folder)
img = Image('logo.png')
ws['A1'] = "Adding image"
#adjusting size
img.height = 130
img.width = 200
#adding img to cell A3

ws.add_image(img, 'A3')

wb.save("new2.xlsx")

Result:

image

CREATING CHARTS

Charts are essential to show a visualization of data. We can create charts from Excel data using the Openpyxl module chart. Different forms of charts such as line charts, bar charts, 3D line charts, etc., can be created. We need to create a reference that contains the data to be used for the chart, which is nothing but a selection of cells (rows and columns). I am using sample data to create a 3D bar chart in the below example:

Example

import openpyxl
from openpyxl
import Workbook
from openpyxl.chart
import BarChart3D, Reference, series

wb = openpyxl.load_workbook("example.xlsx")
ws = wb.active

values = Reference(ws, min_col = 3, min_row = 2, max_col = 3, max_row = 40)
chart = BarChart3D()
chart.add_data(values)
ws.add_chart(chart, "E3")
wb.save("MyChart.xlsx")

Result
image


How to Automate Excel with Python with Video Tutorial

Welcome to another video! In this video, We will cover how we can use python to automate Excel. I'll be going over everything from creating workbooks to accessing individual cells and stylizing cells. There is a ton of things that you can do with Excel but I'll just be covering the core/base things in OpenPyXl.

⭐️ Timestamps ⭐️
00:00 | Introduction
02:14 | Installing openpyxl
03:19 | Testing Installation
04:25 | Loading an Existing Workbook
06:46 | Accessing Worksheets
07:37 | Accessing Cell Values
08:58 | Saving Workbooks
09:52 | Creating, Listing and Changing Sheets
11:50 | Creating a New Workbook
12:39 | Adding/Appending Rows
14:26 | Accessing Multiple Cells
20:46 | Merging Cells
22:27 | Inserting and Deleting Rows
23:35 | Inserting and Deleting Columns
24:48 | Copying and Moving Cells
26:06 | Practical Example, Formulas & Cell Styling

📄 Resources 📄
OpenPyXL Docs: https://openpyxl.readthedocs.io/en/stable/ 
Code Written in This Tutorial: https://github.com/techwithtim/ExcelPythonTutorial 
Subscribe: https://www.youtube.com/c/TechWithTim/featured 

#python 

Monty  Boehm

Monty Boehm

1659453850

Twitter.jl: Julia Package to Access Twitter API

Twitter.jl

A Julia package for interacting with the Twitter API.

Twitter.jl is a Julia package to work with the Twitter API v1.1. Currently, only the REST API methods are supported; streaming API endpoints aren't implemented at this time.

All functions have required arguments for those parameters required by Twitter and an options keyword argument to provide a Dict{String, String} of optional parameters Twitter API documentation. Most function calls will return either a Dict or an Array <: TwitterType. Bad requests will return the response code from the API (403, 404, etc).

DataFrame methods are defined for functions returning composite types: Tweets, Places, Lists, and Users.

Authentication

Before one can make use of this package, you must create an application on the Twitter's Developer Platform.

Once your application is approved, you can access your dashboard/portal to grab your authentication credentials from the "Details" tab of the application.

Note that you will also want to ensure that your App has Read / Write OAuth access in order to post tweets. You can find out more about this on Stack Overflow.

Installation

To install this package, enter ] on the REPL to bring up Julia's package manager. Then add the package:

julia> ]
(v1.7) pkg> add Twitter

Tip: Press Ctrl+C to return to the julia> prompt.

Usage

To run Twitter.jl, enter the following command in your Julia REPL

julia> using Twitter

Then the a global variable has to be declared with the twitterauth function. This function holds the consumer_key(API Key), consumer_secret(API Key Secret), oauth_token(Access Token), and oauth_secret(Access Token Secret) respectively.

twitterauth("6nOtpXmf...", # API Key
            "sES5Zlj096S...", # API Key Secret
            "98689850-Hj...", # Access Token
            "UroqCVpWKIt...") # Access Token Secret
  • Ensure you put your credentials in an env file to avoid pushing your secrets to the public 🙀.

Note: This package does not currently support OAuth authentication.

Code examples

See runtests.jl for example function calls.

using Twitter, Test
using JSON, OAuth

# set debugging
ENV["JULIA_DEBUG"]=Twitter

twitterauth(ENV["CONSUMER_KEY"], ENV["CONSUMER_SECRET"], ENV["ACCESS_TOKEN"], ENV["ACCESS_TOKEN_SECRET"])

#get_mentions_timeline
mentions_timeline_default = get_mentions_timeline()
tw = mentions_timeline_default[1]
tw_df = DataFrame(mentions_timeline_default)
@test 0 <= length(mentions_timeline_default) <= 20
@test typeof(mentions_timeline_default) == Vector{Tweets}
@test typeof(tw) == Tweets
@test size(tw_df)[2] == 30

#get_user_timeline
user_timeline_default = get_user_timeline(screen_name = "randyzwitch")
@test typeof(user_timeline_default) == Vector{Tweets}

#get_home_timeline
home_timeline_default = get_home_timeline()
@test typeof(home_timeline_default) == Vector{Tweets}

#get_single_tweet_id
get_tweet_by_id = get_single_tweet_id(id = "434685122671939584")
@test typeof(get_tweet_by_id) == Tweets

#get_search_tweets
duke_tweets = get_search_tweets(q = "#Duke", count = 200)
@test typeof(duke_tweets) <: Dict

#test sending/deleting direct messages
#commenting out because Twitter API changed. Come back to fix
# send_dm = post_direct_messages_send(text = "Testing from Julia, this might disappear later $(time())", screen_name = "randyzwitch")
# get_single_dm = get_direct_messages_show(id = send_dm.id)
# destroy = post_direct_messages_destroy(id = send_dm.id)
# @test typeof(send_dm) == Tweets
# @test typeof(get_single_dm) == Tweets
# @test typeof(destroy) == Tweets

#creating/destroying friendships
add_friend = post_friendships_create(screen_name = "kyrieirving")

unfollow = post_friendships_destroy(screen_name = "kyrieirving")
unfollow_df = DataFrame(unfollow)
@test typeof(add_friend) == Users
@test typeof(unfollow) == Users
@test size(unfollow_df)[2] == 40

# create a cursor for follower ids
follow_cursor_test = get_followers_ids(screen_name = "twitter", count = 10_000)
@test length(follow_cursor_test["ids"]) == 10_000

# create a cursor for friend ids - use barackobama because he follows a lot of accounts!
friend_cursor_test = get_friends_ids(screen_name = "BarackObama", count = 10_000)
@test length(friend_cursor_test["ids"]) == 10_000

# create a test for home timelines
home_t = get_home_timeline(count = 2)
@test length(home_t) > 1

# TEST of cursoring functionality on user timelines
user_t = get_user_timeline(screen_name = "stefanjwojcik", count = 400)
@test length(user_t) == 400
# get the minimum ID of the tweets returned (the earliest)
minid = minimum(x.id for x in user_t);

# now iterate until you hit that tweet: should return 399
# WARNING: current versions of julia cannot use keywords in macros? read here: https://github.com/JuliaLang/julia/pull/29261
# eventually replace since_id = minid
tweets_since = get_user_timeline(screen_name = "stefanjwojcik", count = 400, since_id = 1001808621053898752, include_rts=1)

@test length(tweets_since)>=399

# testing get_mentions_timeline
mentions = get_mentions_timeline(screen_name = "stefanjwojcik", count = 300) 
@test length(mentions) >= 50 #sometimes API doesn't return number requested (twitter API specifies count is the max returned, may be much lower)
@test Tweets<:typeof(mentions[1])

# testing retweets_of_me
my_rts = get_retweets_of_me(count = 300)
@test Tweets<:typeof(my_rts[1])

Want to contribute?

Contributions are welcome! Kindly refer to the contribution guidelines.

Linux: Build Status 

CodeCov: codecov

Author: Randyzwitch
Source Code: https://github.com/randyzwitch/Twitter.jl 
License: View license

#julia #api #twitter 

Annie  Emard

Annie Emard

1653075360

HAML Lint: Tool For Writing Clean and Consistent HAML

HAML-Lint

haml-lint is a tool to help keep your HAML files clean and readable. In addition to HAML-specific style and lint checks, it integrates with RuboCop to bring its powerful static analysis tools to your HAML documents.

You can run haml-lint manually from the command line, or integrate it into your SCM hooks.

Requirements

  • Ruby 2.4+
  • HAML 4.0+

Installation

gem install haml_lint

If you'd rather install haml-lint using bundler, don't require it in your Gemfile:

gem 'haml_lint', require: false

Then you can still use haml-lint from the command line, but its source code won't be auto-loaded inside your application.

Usage

Run haml-lint from the command line by passing in a directory (or multiple directories) to recursively scan:

haml-lint app/views/

You can also specify a list of files explicitly:

haml-lint app/**/*.html.haml

haml-lint will output any problems with your HAML, including the offending filename and line number.

File Encoding

haml-lint assumes all files are encoded in UTF-8.

Command Line Flags

Command Line FlagDescription
--auto-gen-configGenerate a configuration file acting as a TODO list
--auto-gen-exclude-limitNumber of failures to allow in the TODO list before the entire rule is excluded
-c/--configSpecify which configuration file to use
-e/--excludeExclude one or more files from being linted
-i/--include-linterSpecify which linters you specifically want to run
-x/--exclude-linterSpecify which linters you don't want to run
-r/--reporterSpecify which reporter you want to use to generate the output
-p/--parallelRun linters in parallel using available CPUs
--fail-fastSpecify whether to fail after the first file with lint
--fail-levelSpecify the minimum severity (warning or error) for which the lint should fail
--[no-]colorWhether to output in color
--[no-]summaryWhether to output a summary in the default reporter
--show-lintersShow all registered linters
--show-reportersDisplay available reporters
-h/--helpShow command line flag documentation
-v/--versionShow haml-lint version
-V/--verbose-versionShow haml-lint, haml, and ruby version information

Configuration

haml-lint will automatically recognize and load any file with the name .haml-lint.yml as a configuration file. It loads the configuration based on the directory haml-lint is being run from, ascending until a configuration file is found. Any configuration loaded is automatically merged with the default configuration (see config/default.yml).

Here's an example configuration file:

linters:
  ImplicitDiv:
    enabled: false
    severity: error

  LineLength:
    max: 100

All linters have an enabled option which can be true or false, which controls whether the linter is run, along with linter-specific options. The defaults are defined in config/default.yml.

Linter Options

OptionDescription
enabledIf false, this linter will never be run. This takes precedence over any other option.
includeList of files or glob patterns to scope this linter to. This narrows down any files specified via the command line.
excludeList of files or glob patterns to exclude from this linter. This excludes any files specified via the command line or already filtered via the include option.
severityThe severity of the linter. External tools consuming haml-lint output can use this to determine whether to warn or error based on the lints reported.

Global File Exclusion

The exclude global configuration option allows you to specify a list of files or glob patterns to exclude from all linters. This is useful for ignoring third-party code that you don't maintain or care to lint. You can specify a single string or a list of strings for this option.

Skipping Frontmatter

Some static blog generators such as Jekyll include leading frontmatter to the template for their own tracking purposes. haml-lint allows you to ignore these headers by specifying the skip_frontmatter option in your .haml-lint.yml configuration:

skip_frontmatter: true

Inheriting from Other Configuration Files

The inherits_from global configuration option allows you to specify an inheritance chain for a configuration file. It accepts either a scalar value of a single file name or a vector of multiple files to inherit from. The inherited files are resolved in a first in, first out order and with "last one wins" precedence. For example:

inherits_from:
  - .shared_haml-lint.yml
  - .personal_haml-lint.yml

First, the default configuration is loaded. Then the .shared_haml-lint.yml configuration is loaded, followed by .personal_haml-lint.yml. Each of these overwrite each other in the event of a collision in configuration value. Once the inheritance chain is resolved, the base configuration is loaded and applies its rules to overwrite any in the intermediate configuration.

Lastly, in order to match your RuboCop configuration style, you can also use the inherit_from directive, which is an alias for inherits_from.

Linters

» Linters Documentation

haml-lint is an opinionated tool that helps you enforce a consistent style in your HAML files. As an opinionated tool, we've had to make calls about what we think are the "best" style conventions, even when there are often reasonable arguments for more than one possible style. While all of our choices have a rational basis, we think that the opinions themselves are less important than the fact that haml-lint provides us with an automated and low-cost means of enforcing consistency.

Custom Linters

Add the following to your configuration file:

require:
  - './relative/path/to/my_first_linter.rb'
  - 'absolute/path/to/my_second_linter.rb'

The files that are referenced by this config should have the following structure:

module HamlLint
  # MyFirstLinter is the name of the linter in this example, but it can be anything
  class Linter::MyFirstLinter < Linter
    include LinterRegistry

    def visit_tag
      return unless node.tag_name == 'div'
      record_lint(node, "You're not allowed divs!")
    end
  end
end

For more information on the different types on HAML node, please look through the HAML parser code: https://github.com/haml/haml/blob/master/lib/haml/parser.rb

Keep in mind that by default your linter will be disabled by default. So you will need to enable it in your configuration file to have it run.

Disabling Linters within Source Code

One or more individual linters can be disabled locally in a file by adding a directive comment. These comments look like the following:

-# haml-lint:disable AltText, LineLength
[...]
-# haml-lint:enable AltText, LineLength

You can disable all linters for a section with the following:

-# haml-lint:disable all

Directive Scope

A directive will disable the given linters for the scope of the block. This scope is inherited by child elements and sibling elements that come after the comment. For example:

-# haml-lint:disable AltText
#content
  %img#will-not-show-lint-1{ src: "will-not-show-lint-1.png" }
  -# haml-lint:enable AltText
  %img#will-show-lint-1{ src: "will-show-lint-1.png" }
  .sidebar
    %img#will-show-lint-2{ src: "will-show-lint-2.png" }
%img#will-not-show-lint-2{ src: "will-not-show-lint-2.png" }

The #will-not-show-lint-1 image on line 2 will not raise an AltText lint because of the directive on line 1. Since that directive is at the top level of the tree, it applies everywhere.

However, on line 4, the directive enables the AltText linter for the remainder of the #content element's content. This means that the #will-show-lint-1 image on line 5 will raise an AltText lint because it is a sibling of the enabling directive that appears later in the #content element. Likewise, the #will-show-lint-2 image on line 7 will raise an AltText lint because it is a child of a sibling of the enabling directive.

Lastly, the #will-not-show-lint-2 image on line 8 will not raise an AltText lint because the enabling directive on line 4 exists in a separate element and is not a sibling of the it.

Directive Precedence

If there are multiple directives for the same linter in an element, the last directive wins. For example:

-# haml-lint:enable AltText
%p Hello, world!
-# haml-lint:disable AltText
%img#will-not-show-lint{ src: "will-not-show-lint.png" }

There are two conflicting directives for the AltText linter. The first one enables it, but the second one disables it. Since the disable directive came later, the #will-not-show-lint element will not raise an AltText lint.

You can use this functionality to selectively enable directives within a file by first using the haml-lint:disable all directive to disable all linters in the file, then selectively using haml-lint:enable to enable linters one at a time.

Onboarding Onto a Preexisting Project

Adding a new linter into a project that wasn't previously using one can be a daunting task. To help ease the pain of starting to use Haml-Lint, you can generate a configuration file that will exclude all linters from reporting lint in files that currently have lint. This gives you something similar to a to-do list where the violations that you had when you started using Haml-Lint are listed for you to whittle away, but ensuring that any views you create going forward are properly linted.

To use this functionality, call Haml-Lint like:

haml-lint --auto-gen-config

This will generate a .haml-lint_todo.yml file that contains all existing lint as exclusions. You can then add inherits_from: .haml-lint_todo.yml to your .haml-lint.yml configuration file to ensure these exclusions are used whenever you call haml-lint.

By default, any rules with more than 15 violations will be disabled in the todo-file. You can increase this limit with the auto-gen-exclude-limit option:

haml-lint --auto-gen-config --auto-gen-exclude-limit 100

Editor Integration

Vim

If you use vim, you can have haml-lint automatically run against your HAML files after saving by using the Syntastic plugin. If you already have the plugin, just add let g:syntastic_haml_checkers = ['haml_lint'] to your .vimrc.

Vim 8 / Neovim

If you use vim 8+ or Neovim, you can have haml-lint automatically run against your HAML files as you type by using the Asynchronous Lint Engine (ALE) plugin. ALE will automatically lint your HAML files if it detects haml-lint in your PATH.

Sublime Text 3

If you use SublimeLinter 3 with Sublime Text 3 you can install the SublimeLinter-haml-lint plugin using Package Control.

Atom

If you use atom, you can install the linter-haml plugin.

TextMate 2

If you use TextMate 2, you can install the Haml-Lint.tmbundle bundle.

Visual Studio Code

If you use Visual Studio Code, you can install the Haml Lint extension

Git Integration

If you'd like to integrate haml-lint into your Git workflow, check out our Git hook manager, overcommit.

Rake Integration

To execute haml-lint via a Rake task, make sure you have rake included in your gem path (e.g. via Gemfile) add the following to your Rakefile:

require 'haml_lint/rake_task'

HamlLint::RakeTask.new

By default, when you execute rake haml_lint, the above configuration is equivalent to running haml-lint ., which will lint all .haml files in the current directory and its descendants.

You can customize your task by writing:

require 'haml_lint/rake_task'

HamlLint::RakeTask.new do |t|
  t.config = 'custom/config.yml'
  t.files = ['app/views', 'custom/*.haml']
  t.quiet = true # Don't display output from haml-lint to STDOUT
end

You can also use this custom configuration with a set of files specified via the command line:

# Single quotes prevent shell glob expansion
rake 'haml_lint[app/views, custom/*.haml]'

Files specified in this manner take precedence over the task's files attribute.

Documentation

Code documentation is generated with YARD and hosted by RubyDoc.info.

Contributing

We love getting feedback with or without pull requests. If you do add a new feature, please add tests so that we can avoid breaking it in the future.

Speaking of tests, we use Appraisal to test against both HAML 4 and 5. We use rspec to write our tests. To run the test suite, execute the following from the root directory of the repository:

appraisal bundle install
appraisal bundle exec rspec

Community

All major discussion surrounding HAML-Lint happens on the GitHub issues page.

Changelog

If you're interested in seeing the changes and bug fixes between each version of haml-lint, read the HAML-Lint Changelog.

Author: sds
Source Code: https://github.com/sds/haml-lint
License: MIT license

#haml #lint 

坂本  篤司

坂本 篤司

1654310040

TypeScriptとgraphql-requestを使用してNode.jsでGraphQLアプリを構築します

この記事では、バックエンドでGraphQLとNode.jsを使用してフルスタックアプリを構築します。一方、フロントエンドはgraphql-requestライブラリを使用してバックエンドでネットワーク操作を実行します。

なぜgraphql-requestとTypeScriptを使用するのですか?

開発者がApolloを使用してGraphQLサーバーを構築するときはいつでも、ライブラリは次のような「フロントエンド」を生成します。

このインターフェースにより、ユーザーはコードを介してサーバーにクエリまたはミューテーション要求を行うことができます。ただし、部屋の中の象について説明しましょう。あまりユーザーフレンドリーではないようです。フロントエンドにはボタンや便利なインターフェース要素がないため、多くのユーザーがアプリ内を移動するのは難しいかもしれません。その結果、これによりユーザーベースが縮小します。では、この問題をどのように解決するのでしょうか。

これがgraphql-request出番です。これは、ユーザーがGraphQLサーバーでクエリを実行できるようにするオープンソースライブラリです。次の機能を備えています。

  • 軽量—このライブラリは21キロバイトをわずかに超える最小化されているため、アプリのパフォーマンスを維持できます
  • PromiseベースのAPI—これにより非同期アプリケーションのサポートがもたらされます
  • TypeScriptのサポート—TypeScriptgraphql-requestを可能にする多くのライブラリの1つです。Typescriptの主な利点の1つは、安定した予測可能なコードが可能になることです。

たとえば、次のプログラムを見てください。

let myNumber = 9; //here, myNumber is an integer
myNumber = 'hello'; //now it is a string.
myNumber = myNumber + 10; //even though we are adding a string to an integer,
//JavaScript won't return an error. In the real world, it might bring unexpected outputs.
//However, in Typescript, we can tell the compiler..
//what data types we need to choose.
let myNumber:number = 39; //tell TS that we want to declare an integer.
myNumber = 9+'hello'; //returns an error. Therefore, it's easier to debug the program
//this promises stability and security. 

この記事では、GraphQLとTypeScriptを使用してフルスタックアプリを構築します。ここでは、apollo-server-expressパッケージを使用してバックエンドサーバーを構築します。さらに、フロントエンドでは、Nextを使用graphql-requestしてGraphQLAPIを使用します。

サーバーの構築

プロジェクトの初期化

空のNode.jsプロジェクトを初期化するには、次のターミナルコマンドを実行します。

mkdir graphql-ts-tutorial #create project folder 
cd graphql-ts-tutorial 
npm init -y #initialize the app

それが終わったら、コードベースでTypeScriptを使用する必要があることをNodeに通知する必要があります。

#configure our Typescript:
npx tsc --init --rootDir app --outDir dist --esModuleInterop --resolveJsonModule --lib es6 --module commonjs --allowJs true --noImplicitAny true
mkdir app #our main code folder
mkdir dist #Typescript will use this folder to compile our program.

次に、次の依存関係をインストールします。

#development dependencies. Will tell Node that we will use Typescript
npm install -d ts-node @types/node typescript @types/express nodemon
#Installing Apollo Server and its associated modules. Will help us build our GraphQL
#server
npm install apollo-server-express apollo-server-core express graphql

この手順の後、appフォルダに移動します。ここで、次のファイルを作成します。

  • index.ts:メインファイル。これにより、ExpressGraphQLサーバーが実行されます。
  • dataset.ts:これは、クライアントに提供されるデータベースとして機能します
  • Resolvers.ts:このモジュールはユーザーコマンドを処理します。リゾルバーについては、この記事の後半で学習します
  • Schema.ts:名前が示すように、このファイルには、クライアントにデータを送信するために必要な回路図が保存されます

最終的に、フォルダ構造は次のようになります。

データベースの作成

このセクションでは、要求されたデータを送信するために使用されるダミーデータベースを作成します。これを行うには、に移動しapp/dataset.tsて次のコードを記述します。

let people: { id: number; name: string }[] = [
  { id: 1, name: "Cassie" },
  { id: 2, name: "Rue" },
  { id: 3, name: "Lexi" },
];
export default people;
  • まず、というオブジェクトの配列を作成しましたpeople
  • この配列には、タイプとidタイプの2つのフィールドがあります。numbernamestring

スキーマの定義

ここでは、GraphQLサーバーのスキーマを作成します。

簡単に言うと、GraphQLスキーマは、クライアントがAPIから要求できるデータセットの記述です。この概念は、マングースライブラリの概念に似ています。
スキーマを作成するには、app/Schema.tsファイルに移動します。そこで、次のコードを記述します。

import { gql } from "apollo-server-express"; //will create a schema
const Schema = gql`
  type Person {
    id: ID!
    name: String
  }
  #handle user commands
  type Query {
    getAllPeople: [Person] #will return multiple Person instances
    getPerson(id: Int): Person #has an argument of 'id` of type Integer.
  }
`;
export default Schema; 
//export this Schema so we can use it in our project

このコードを1つずつ分解してみましょう。

  • 変数にはSchemaGraphQLスキーマが含まれています
  • まず、Personスキーマを作成しました。idタイプIDnameタイプの2つのフィールドがありますString
  • 後で、クライアントがコマンドを実行すると、サーバーがオブジェクトgetAllPeopleの配列を返すようにGraphQLに指示しました。Person
  • さらに、ユーザーがgetPersonコマンドを使用すると、GraphQLは単一のPersonインスタンスを返します

リゾルバーの作成

スキーマをコーディングしたので、次のステップはリゾルバーを定義することです。
簡単に言うと、リゾルバーはGraphQLクエリの応答を生成する関数のグループです。つまり、リゾルバーはGraphQLクエリハンドラーとして機能します。
Resolvers.ts、次のコードを記述します。

import people from "./dataset"; //get all of the available data from our database.
const Resolvers = {
  Query: {
    getAllPeople: () => people, //if the user runs the getAllPeople command
    //if the user runs the getPerson command:
    getPerson: (_: any, args: any) => { 
      console.log(args);
      //get the object that contains the specified ID.
      return people.find((person) => person.id === args.id);
    },
  },
};
export default Resolvers;
  • ここではQuery、サーバーに送信されるすべての着信クエリを処理するオブジェクトを作成しました
  • ユーザーがgetAllPeopleコマンドを実行すると、プログラムはデータベースに存在するすべてのオブジェクトを返します
  • さらに、getPersonコマンドには引数が必要idです。Personこれにより、IDが一致するインスタンスが返されます
  • 最終的に、アプリとリンクできるようにリゾルバーをエクスポートしました

サーバーの構成

ほぼ完了です。スキーマとリゾルバーの両方を構築したので、次のステップはそれらをリンクすることです。

index.js、次のコードブロックを記述します。

import { ApolloServer } from "apollo-server-express";
import Schema from "./Schema";
import Resolvers from "./Resolvers";
import express from "express";
import { ApolloServerPluginDrainHttpServer } from "apollo-server-core";
import http from "http";

async function startApolloServer(schema: any, resolvers: any) {
  const app = express();
  const httpServer = http.createServer(app);
  const server = new ApolloServer({
    typeDefs: schema,
    resolvers,
    //tell Express to attach GraphQL functionality to the server
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
  }) as any;
  await server.start(); //start the GraphQL server.
  server.applyMiddleware({ app });
  await new Promise<void>((resolve) =>
    httpServer.listen({ port: 4000 }, resolve) //run the server on port 4000
  );
  console.log(`Server ready at http://localhost:4000${server.graphqlPath}`);
}
//in the end, run the server and pass in our Schema and Resolver.
startApolloServer(Schema, Resolvers);

テストしてみましょう!コードを実行するには、次のBashコマンドを使用します。

npx nodemon app/index.ts 

これにより、URLにサーバーが作成されlocalhost:4000/graphqlます。

ここで、UI内で使用可能なスキーマを確認できます。

これは、コードが機能することを意味します。

すべてのGraphQLクエリは操作パネル内にあります。実際の動作を確認するには、次のボックスに次のスニペットを入力してください。

#make a query:
query {
  #get all of the people available in the server
  getAllPeople {
    #procure their IDs and names.
    id
    name
  }
}

結果を確認するには、[実行]ボタンをクリックします。

getPersonクエリを介して特定のエンティティを検索することもできます。

query ($getPersonId: Int) { #the argument will be of type Integer
  getPerson(id: 1) {
    #get the person with the ID of 1
    name
    id
  }
}

突然変異の作成

GraphQLの世界では、ミューテーションはデータベースに副作用をもたらすコマンドです。この一般的な例は次のとおりです。

  • データベースへのユーザーの追加—クライアントがWebサイトにサインアップすると、ユーザーはミューテーションを実行してデータをデータベースに保存します
  • オブジェクトの編集または削除—ユーザーがデータベースからデータを変更または削除した場合、基本的にサーバー上にミューテーションが作成されます。

ミューテーションを処理するには、Schema.tsモジュールに移動します。ここで、Schema変数内に次のコード行を追加します。

const Schema = gql`
  #other code..
  type Mutation {
    #the addPerson commmand will accept an argument of type String.
    #it will return a 'Person' instance. 
    addPerson(name: String): Person
  }
`;

次のステップは、このミューテーションを処理するためのリゾルバーを作成することです。これを行うには、Resolvers.tsファイル内に次のコードブロックを追加します。

const Resolvers = {
  Query: {
    //..further code..
  },
  //code to add:
  //all our mutations go here.
  Mutation: {
    //create our mutation:
    addPerson: (_: any, args: any) => {
      const newPerson = {
        id: people.length + 1, //id field
        name: args.name, //name field
      };
      people.push(newPerson);
      return newPerson; //return the new object's result
    },
  },
};
  • 突然変異は引数addPersonを受け入れますname
  • aが渡されると、プログラムは一致するキーnameを持つ新しいオブジェクトを作成しますname
  • 次に、メソッドを使用してこのオブジェクトをデータセットpushに追加しますpeople
  • 最後に、新しいオブジェクトのプロパティをクライアントに返します

それでおしまい!テストするには、[操作]ウィンドウ内で次のコードを実行します。

#perform a mutation on the server
mutation($name: String) {
  addPerson(name:"Hussain") { #add a new person with the name "Hussain"
    #if the execution succeeds, return its 'id' and 'name` to the user.
    id
    name
  }
}

GraphQLがデータベースに新しいエントリを追加したかどうかを確認しましょう。

query {
  getAllPeople { #get all the results within the 'people' database. 
  #return only their names
  name 
  }
}

クライアントの構築

サーバーの構築に成功しました。このセクションでは、Nextを使用して、サーバーをリッスンし、UIにデータをレンダリングするクライアントアプリを構築します。

最初のステップとして、次のように空のNext.jsアプリを初期化します。

npx create-next-app@latest graphql-client --ts
touch constants.tsx #our query variables go here.

GraphQL操作を実行するには、graphql-requestライブラリーを使用します。これは最小限のオープンソースモジュールであり、サーバーでミューテーションとクエリを実行するのに役立ちます。

npm install graphql-request graphql
npm install react-hook-form #to capture user input

クエリ変数の作成

このセクションでは、GraphQL操作を行うのに役立つクエリとミューテーションをコーディングします。これを行うには、に移動しconstants.tsxて次のコードを追加します。

import { gql } from "graphql-request";
//create our query
const getAllPeopleQuery = gql`
  query {
    getAllPeople { #run the getAllPeople command
      id
      name
    }
  }
`;
//Next, declare a mutation
const addPersonMutation = gql`
  mutation addPeople($name: String!) {
    addPerson(name: $name) { #add a new entry. Argument will be 'name'
      id
      name
    }
  }
`;
export { getAllPeopleQuery, addPersonMutation };
  • 最初の部分では、getAllPeopleQuery変数を作成しました。ユーザーがこのクエリを実行すると、プログラムはサーバーにデータベースに存在するすべてのエントリを取得するように指示します
  • 後で、addPersonミューテーションはGraphQLに、尊重されたnameフィールドを持つ新しいエントリを追加するように指示します
  • 最後に、exportキーワードを使用して変数をプロジェクトの残りの部分にリンクしました

クエリの実行

pages/index.ts、次のコードを記述します。

import type { NextPage, GetStaticProps, InferGetStaticPropsType } from "next";
import { request } from "graphql-request"; //allows us to perform a request on our server
import { getAllPeopleQuery } from "../constants"; 
import Link from "next/link";
const Home: NextPage = ({
  result, //extract the 'result' prop 
}: InferGetStaticPropsType<typeof getStaticProps>) => {
  return (
    <div className={styles.container}>
      {result.map((item: any) => { //render the 'result' array to the UI 
        return <p key={item.id}>{item.name}</p>;
      })}
    <Link href="/addpage">Add a new entry </Link>
    </div>
  );
};
//fetch data from the server
export const getStaticProps: GetStaticProps = async () => {
  //the first argument is the URL of our GraphQL server
  const res = await request("http://localhost:4000/graphql", getAllPeopleQuery);
  const result = res.getAllPeople;
  return {
    props: {
      result,
    }, // will be passed to the page component as props
  };
};
export default Home;

このコードの内訳は次のとおりです。

  • このメソッドでは、GraphQLサーバーでコマンドgetStaticPropsを実行するようにNextに指示しましたgetAllPeople
  • Homeその後、機能コンポーネントへの応答を返しました。これは、結果をUIにレンダリングできることを意味します
  • 次に、プログラムはこのメソッドを使用して、コマンドのすべての結果をUImapにレンダリングしました。getAllPeople各段落要素にはname、各エントリのフィールドが表示されます
  • さらに、コンポーネントを使用してユーザーをルートLinkにリダイレクトしました。addpageこれにより、ユーザーPersonはテーブルに新しいインスタンスを追加できます

コードをテストするには、次のターミナルコマンドを実行します。

npm run dev

これが結果になります:

GraphQLサーバーはリアルタイムで更新されます。

突然変異の実行

graphql-requestクエリの実行に成功したので、ライブラリを介してミューテーションを実行することもできます。

フォルダ内pagesに、という名前の新しいファイルを作成しますaddpage.tsx。名前が示すように、このコンポーネントを使用すると、ユーザーはデータベースに新しいエントリを追加できます。ここでは、次のコードブロックを作成することから始めます。

import type { NextPage, GetStaticProps, InferGetStaticPropsType } from "next";
import { request } from "graphql-request";
import { addPersonMutation } from "../constants";
const AddPage: NextPage = () => {
  return (
    <div>
      <p>We will add a new entry here. </p>
    </div>
  );
};
export default AddPage;

このコードでは、テキストを含む空白のページを作成しています。これは、URLルーティングシステムが機能するかどうかを確認するために行っています。

これは、ルーティングを正常に使用したことを意味します。次に、このスニペットをaddpage.tsxファイルに書き込みます。

import { useForm } from "react-hook-form";
const { register, handleSubmit } = useForm();
//if the user submits the form, then the program will output the value of their input.
const onSubmit = (data: any) => console.log(data);
return (
  <div>
    <form onSubmit={handleSubmit(onSubmit)}> {/*Bind our handler to this form.*/}
      {/* The user's input will be saved within the 'name' property */}
      <input defaultValue="test" {...register("name")} />
      <input type="submit" />
    </form>
  </div>
);

これが出力になります:

 

ユーザーの入力を正常にキャプチャしたので、最後のステップはサーバーにユーザーのエントリを追加することです。

これを行うには、ファイルにあるonSubmitハンドラーを次のように変更します。pages/addpage.tsx

const onSubmit = async (data: any) => {
  const response = await request(
    "http://localhost:4000/graphql",
    addPersonMutation,
    data
  );
  console.log(response);
};
  • requestここでは、関数を介してGraphQLサーバーへのミューテーションリクエストを実行しています
  • さらに、addPersonmutationコマンドをリクエストヘッダーにも渡しました。これにより、GraphQLにaddMutationサーバーでアクションを実行するように指示されます

これが結果になります:

これで完了です。

結論

これがこのプロジェクトの完全なソースコードです。

この記事では、GraphQLとTypeScriptを使用してフルスタックアプリを作成する方法を学びました。これらは両方とも、今日需要が高いため、プログラミングの世界では非常に重要なスキルです。

このコードで問題が発生した場合は、この概念を完全に理解できるように、コードを分解して試してみることをお勧めします。

読んでくれてありがとう!ハッピーコーディング!

このストーリーは、もともとhttps://blog.logrocket.com/build-graphql-app-node-js-typescript-graphql-request/で公開されました

#graphql #typescript #nodejs